How to use the ruby โ€‹โ€‹"case ... when" with inequality?

can you do it in ruby? he seems to โ€œskipโ€ cases with inequalities

case myvar when myvar < -5 do somethingA when -5..-3 do special_something_XX when -2..-1 do special_something_YY when myvar == 0 do somethingB when myvar > 0 go somethingC end 
+43
ruby switch-statement
Feb 25 2018-11-11T00:
source share
5 answers

You mix two different types of case statements:

 case var when 1 dosomething when 2..3 doSomethingElse end case when var == 1 doSomething when var < 12 doSomethingElse end 
+86
Feb 25 '11 at 7:20
source share
  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 
+23
Dec 11 '12 at 7:16
source share

Iโ€™m personally not sure if youโ€™d better not work with if statements, but if you want to find a solution in this form:

 Inf = 1.0/0 case myvar when -Inf..-5 do somethingA when -5..-3 do special_something_XX when -2..-1 do special_something_YY when 0 do somethingB when 0..Inf do somethingC end 

The following is my decision. Here, the order matters, and you need to repeat myvar , but itโ€™s much harder not to take cases into account, you donโ€™t need to repeat each binding twice, and the rigor ( < vs <= , not .. vs ... ) is much more obvious.

 if myvar <= -5 # less than -5 elsif myvar <= -3 # between -5 and -3 elsif myvar <= -1 # between -3 and -1 elsif myvar <= 0 # between -1 and 0 else # larger than 0 end 
+6
Feb 25 '11 at 7:19
source share
 def project_completion(percent) case percent when percent..25 "danger" when percent..50 "warning" when percent..75 "info" when percent..100 "success" else "info" end end 
+3
Dec 11 '14 at 8:48
source share

Using infinity may help

 case var when -Float::INFINITY..-1 when 0 when 1..2 when 3..Float::INFINITY end 
0
Aug 02 '16 at 17:41
source share



All Articles