I have an instance variable @limit
which must be greater than 0 and no greater than 20. I currently have code like this:
@limit = (params[:limit] || 10).to_i
@limit = 20 if @limit > 20
@limit = 0 if @limit < 0
This looks ugly. Is there a better way to restrict an integer to a range of values?
Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.
There are two methods you can use when working with Ruby ranges. These are the include and the cover. The include method works by checking if a value is in the range, while the cover checks the initial and ending value of the range for a match.
In Ruby, one can use get. chmop. to_i to take integer inputs from user. In this example, the class of a is Fixnum and this shows that a is an integer.
Comparable#clamp
is available in Ruby 2.4.
3.clamp(10, 20)
=> 10
27.clamp(10, 20)
=> 20
15.clamp(10, 20)
=> 15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With