Determining if a variable is within range?

I need to write a loop that does something like:

if i (1..10)
  do thing 1
elsif i (11..20)
  do thing 2
elsif i (21..30)
  do thing 3
etc...

But so far have gone down the wrong paths in terms of syntax.


Solution 1:

if i.between?(1, 10)
  do thing 1 
elsif i.between?(11,20)
  do thing 2 
...

Solution 2:

Use the === operator (or its synonym include?)

if (1..10) === i

Solution 3:

As @Baldu said, use the === operator or use case/when which internally uses === :

case i
when 1..10
  # do thing 1
when 11..20
  # do thing 2
when 21..30
  # do thing 3
etc...

Solution 4:

if you still wanted to use ranges...

def foo(x)
 if (1..10).include?(x)
   puts "1 to 10"
 elsif (11..20).include?(x)
   puts "11 to 20"
 end
end

Solution 5:

You can usually get a lot better performance with something like:

if i >= 21
  # do thing 3
elsif i >= 11
  # do thing 2
elsif i >= 1
  # do thing 1