Skip to content

Latest commit

 

History

History
22 lines (18 loc) · 632 Bytes

clamp-to-an-endless-range.md

File metadata and controls

22 lines (18 loc) · 632 Bytes

Clamp To An Endless Range

The Comparable#clamp method allows us to specify the bounds of a value we want. If the target value is between the bounds, then we get that value. Otherwise, we gets the nearest end of the bounds.

We can even pass a range to #clamp instead of separate lower and upper bound values. Because Ruby has beginless and endless ranges, this gives us the ergonomics to, say, clamp to any non-negative value with a 0.. endless range.

Here is what that looks like:

> 22.clamp(0..)
=> 22
> (-33).clamp(0..)
=> 0
> 0.clamp(0..)
=> 0