Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict an integer to a range in Ruby

Tags:

ruby

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?

like image 821
superluminary Avatar asked Dec 03 '13 13:12

superluminary


People also ask

How do you set a range in Ruby?

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.

How do you check if a number is in a range Ruby?

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.

How do you input an integer in Ruby?

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.


1 Answers

Comparable#clamp is available in Ruby 2.4.

3.clamp(10, 20)
=> 10

27.clamp(10, 20)
=> 20

15.clamp(10, 20)
=> 15
like image 78
Ryan McGeary Avatar answered Oct 22 '22 05:10

Ryan McGeary