结构
case a
when x
code_x
when y
code_y
else
code_z
end
相同的计算结果为
if x === a
code_x
elsif y === a
code_y
else
code_z
end
每个when
调用的when
参数的方法===
,传球case
参数作为参数(x === a
是相同的x.===(a)
) 。 ===
方法与==
稍有不同:它通常被称为“个案包容”。对于数字和字符串等简单类型,它与==
是一样的。对于Range
和Array
对象,它是.include?
的同义词。对于Regexp
对象,它与match
非常相似。对于Module
对象,它会测试参数是否为该模块的实例或其后代的一个实例(基本上,如果x === a
,则为a.instance_of?(x)
)。因此,在你的代码,
if (1..101) === i
...
elsif (i == 101) === i
...
else
...
end
执行几乎同样的测试,
if (1..101).include?(i)
...
elsif (i == 101) == i
...
else
...
end
注意,这里的case
另一种形式的不使用===
:
case
when x
code_x
when y
code_y
else
code_z
end
这等同于
if x
code_x
elsif y
code_y
else
code_z
end
读者:如果你看到这个答案和我的一些相似之处,你应该知道我的原始答案是不正确的混乱,这并没有被这个戴头盔的Rubiest所忽略。在我完成编辑的同时,他提交了他的答案。 –