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 opera开发者_Go百科tor you're looking for.
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
do_something if (3..9).include?( x ) # inclusive
do_something if (3...10).include?( x ) # inclusive start, exclusive end
See the Range
class; you can read an introduction to them hosted on my website.
Comparable#between?
do_something if x.between?(2, 10)
Something like this?
do_something if (3..9) === x
or
r = 3..9
if r === x
. . .
精彩评论