Clamp

image by Matt Artz

Clamp for min/max values

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.

RailsConf 2024

I'm co-chairing RailsConf 2024 in Detroit May 7–9. Come and join us 

Instead of…

…using Array#min and 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

Use…

…Ruby’s #clamp method.

value = 1000
value.clamp(0, 255)
#=> 255

value = -100
value.clamp(0, 255)
#=> 0

Why?

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?

Why not?

There’s no reason not to. Maybe you like the look of confusing square brackets?

Thanks

My appreciation to Justin for pointing out my pre-2.4 Ruby.

Brighton Ruby 2024

Still running UK’s friendliest, Ruby event on Friday 28th June. Ice cream + 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.