Backo Backo - 1 year ago 91
Ruby Question

How to check if a number is included in a range (in one statement)?

I am using Ruby on Rails 3.0.9 and I would like to check if a number is included in a range. That is, if I have a variable

number = 5
I would like to check
1 <= number <= 10
and retrieve a boolean value if the
value is included in that range.

I can do that like this:

number >= 1 && number <= 10

but I would like to do that in one statement. How can I do that?

Answer Source

(1..10).include?(number) is the trick.

Btw: If you want to validate a number using ActiveModel::Validations, you can even do:

validates_inclusion_of :number, :in => 1..10

read here about validates_inclusion_of

or the Rails 3 way:

validates :number, :inclusion => 1..10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download