如何使用ruby“case ... when”与不等式?

时间:2011-02-25 07:09:41

标签: ruby switch-statement

你能用红宝石做到这一点吗? 它似乎“错过”了不平等的案件

 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

5 个答案:

答案 0 :(得分:97)

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

case var
when 1
  dosomething
when 2..3
  doSomethingElse
end

case
when var == 1
   doSomething
when var < 12
   doSomethingElse
end

答案 1 :(得分:26)

   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

答案 2 :(得分:7)

我个人并不相信if语句不会更好,但是如果你想要这种形式的解决方案:

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

我的首选解决方案如下。这里的顺序很重要,你必须重复myvar,但是要省略案例要困难得多,你不必重复每个边界两次,严格性(< vs {{1}而不是<= vs ..)更加明显。

...

答案 3 :(得分:4)

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

答案 4 :(得分:1)

使用infinity可能会有所帮助

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