how to use ruby " case ... when " with inequalities?
You are mixing two different types of case statements:
case varwhen 1 dosomethingwhen 2..3 doSomethingElseendcasewhen var == 1 doSomethingwhen var < 12 doSomethingElseend
case myvar when proc { |n| n < -5 } do somethingA when -5..-3 do special_something_XX when -2..-1 do special_something_YY when proc { |n| n == 0 } do somethingB when proc { |n| n > 0 } go somethingC end end
I am not personally convinced that you wouldn't be better off with if statements, but if you want a solution in that form:
Inf = 1.0/0case myvarwhen -Inf..-5 do somethingAwhen -5..-3 do special_something_XXwhen -2..-1 do special_something_YYwhen 0 do somethingBwhen 0..Inf do somethingCend
My preferred solution follows. Here the order matters and you have to repeat the myvar
, but it's much harder to leave out cases, you don't have to repeat each bound twice, and the strictness (<
vs <=
rather than ..
vs ...
) is much more obvious.
if myvar <= -5 # less than -5elsif myvar <= -3 # between -5 and -3elsif myvar <= -1 # between -3 and -1elsif myvar <= 0 # between -1 and 0else # larger than 0end