image by Matt Artz
In my article on value objects, the example involved constraining an integer to a minimum and maximum value in the
#initialize method. As of Ruby 2.4, there’s a handy method for that:
#clamp. The documentation for the method is in the Comparable module.
Array#max to constrain a value within a range:
value = 1000 [[0, value].max], 255].min #=> 255 value = -100 [[0, value].max], 255].min #=> 0
value = 1000 value.clamp(0, 255) #=> 255 value = -100 value.clamp(0, 255) #=> 0
The standard library is deliberately expansive and elegant.
This is the exact use case for the problem I was trying to solve, so why use more verbose syntax?
There’s no reason not to. Maybe you like the look of confusing square brackets?
My appreciation to Justin for pointing out my pre-2.4 Ruby.
Last updated on August 11th, 2019 by @andycroll
An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.