Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby shortcut for "if (number in range) then..."

Is there a Ruby shortcut for the following?

if (x > 2) and (x < 10)
  do_something_here
end

I thought I saw something to that effect, but cannot find a reference to it. Of course it's hard to lookup when you don't know what operator you're looking for.

like image 314
jpw Avatar asked May 25 '11 21:05

jpw


1 Answers

if (3..9).include? x
  # whatever
end

As a sidenote, you can also use the triple equals operator for ranges:

if (3..9) === x
  # whatever
end

This lets you use them in case statements as well:

case x
  when 3..9
    # Do something
  when 10..17
    # Do something else
end
like image 86
PreciousBodilyFluids Avatar answered Oct 18 '22 04:10

PreciousBodilyFluids