I wanted to check if my_number was in a certain range, including the higher Value.
In an IF Statement I\'d simply use \"x > 100 && x <= 500\"
But
It should just work like you said. The below case construct includes the value 500.
case my_number
# between 100 and 500
when 100..500
puts "Correct, do something"
end
So:
case 500
when 100..500
puts "Yep"
end
will return Yep
Or would you like to perform a separate action if the value is exactly 500?
when -Float::INFINITY..0
Would do the trick :)
You could just do:
(1..500).include? x
which is also aliased as member?.
Here's a case way to capture "x > 100 && x <= 500 as desired: a value in a closed range with the start value excluded and the end value included. Also, capturing the ranges before and after that is shown.
case my_number
when ..100; puts '≤100'
when 100..500; puts '>100 and ≤500'
when 500..; puts '>500'
end
Explanations:
-Infinity resp. go to Infinity. This was introduced in Ruby 2.6.x..y include the end value, ranges x...y exclude the end value.when case. That is how the second when case is equivalent to your "x > 100 && x <= 500 even though (100..500).include? 100. Similarly for the third case.