68

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.

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227

5 Answers5

154

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.

Akshay Mohite
  • 2,168
  • 1
  • 16
  • 22
  • Also covered in the [Ruby community style guide](https://github.com/bbatsov/ruby-style-guide/commit/1b8c788c836f00507056eba21d4b9ca8078eec3e). – Dennis Feb 21 '14 at 18:37
22

You can use the === operator:

(1..10) === 1 #=> true
(1..10) === 100 #=> false
Community
  • 1
  • 1
Rudy Matela
  • 6,310
  • 2
  • 32
  • 37
  • 8
    Just note, when using this solution I found that You need to be aware of order in which is condition written `1 === (1..10)` will produce false – Kovo Nov 04 '18 at 23:40
12

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

 (1..10).member?(1)   => true
 (1..10).member?(100) => false 
Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
9
(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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

have a look at this question: Determining if a variable is within range?

Community
  • 1
  • 1
Raoul Duke
  • 4,241
  • 2
  • 23
  • 18