diff --git a/README.md b/README.md index 5928b51..7b82765 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1548 TILs and counting..._ +_1549 TILs and counting..._ --- @@ -1217,6 +1217,7 @@ _1548 TILs and counting..._ - [Check If A URL Resolves To 200](ruby/check-if-a-url-resolves-to-200.md) - [Check If An Object Includes A Module](ruby/check-if-an-object-includes-a-module.md) - [Check Return Status Of Running A Shell Command](ruby/check-return-status-of-running-a-shell-command.md) +- [Clamp To An Endless Range](ruby/clamp-to-an-endless-range.md) - [Click On Text With Capybara](ruby/click-on-text-with-capybara.md) - [Colorful Output With MiniTest](ruby/colorful-output-with-minitest.md) - [Comparing Class Hierarchy Relationships](ruby/comparing-class-hierarchy-relationships.md) diff --git a/ruby/clamp-to-an-endless-range.md b/ruby/clamp-to-an-endless-range.md new file mode 100644 index 0000000..eb78f28 --- /dev/null +++ b/ruby/clamp-to-an-endless-range.md @@ -0,0 +1,22 @@ +# Clamp To An Endless Range + +The +[`Comparable#clamp`](https://ruby-doc.org/3.3.6/Comparable.html#method-i-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: + +```ruby +> 22.clamp(0..) +=> 22 +> (-33).clamp(0..) +=> 0 +> 0.clamp(0..) +=> 0 +```