如何使用ruby“的情况下……当”不平等?

你能用ruby做这个吗? 似乎“错过”了不平等的情况

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 

您正在混合两种不同types的案例陈述:

 case var when 1 dosomething when 2..3 doSomethingElse end case when var == 1 doSomething when var < 12 doSomethingElse end 
  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 

我个人不相信,如果你的陈述不会更好,但是如果你想要一个这样的解决scheme:

 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 

我的首选scheme如下。 这里的顺序很重要,你必须重复myvar ,但是更难删除的情况下,你不必重复每次绑定两次,严格( < vs <=而不是.. vs ... )是更明显。

 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 
 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 

使用无限可能会有所帮助

 case var when -Float::INFINITY..-1 when 0 when 1..2 when 3..Float::INFINITY end