Check if an integer is within a range [duplicate]

Is there a simple way to evaluate whether an integer is within that range using the (2..100) syntax.

For example, say I wanted to evaluate as true if my integer x = 100, and my range is (0..200), I'm just looking for the simple, concise ruby-way of doing this.


There are many ways of doing the same things in Ruby. You can check if value is in the range by use of following methods,

14.between?(10,20) # true

(10..20).member?(14) # true

(10..20).include?(14) # true

But, I would suggest using between? rather than member? or include?

All number literals denote inclusive ranges. You can find more about it on Ruby in Rails.


You can use the === operator:

(1..10) === 1 #=> true
(1..10) === 100 #=> false

you can use the member? method of the range to test this

 (1..10).member?(1)   => true
 (1..10).member?(100) => false 

(2..100).include?(5) #=> true
(2..100).include?(200) #=> false

Note that 2..0 is an empty range, so (2..0).include?(x) will return false for all values of x.