如何在Ruby中进行数值比较?

时间:2016-08-21 03:23:03

标签: ruby

为什么以下输出else部分?

some_value = 100

case some_value
when some_value <= 200
  puts "less than 200"
else
  puts "not less than 200"
end

1 个答案:

答案 0 :(得分:3)

case...when...end构造使用===来检查匹配。

您的代码评估为:

case 100
when some_value <= 200 # when (some_value <= 200) === 100, which is (true === 100), which doesn't match
  puts "less than 200"
else
  puts "not less than 200"
end

您可以省略case之后的值,使构造的行为类似于if...else...

some_value = 100

case
when some_value <= 200
  puts "less than 200"
else
  puts "not less than 200"
end