Ruby使用的是case
expression.
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end
Ruby使用===
运算符将when
子句中的对象与case
子句中的对象进行比较.例如,1..5 === x
,而不是x === 1..5
.
如上所示,这允许使用复杂的when
个子句.范围、等级和各种各样的东西都可以测试,而不仅仅是平等.
与许多其他语言中的switch
条语句不同,Ruby的case
没有fall-through条语句,因此没有必要在when
的末尾加上break
.您还可以在一个when
子句(如when "foo", "bar"
)中指定多个匹配项.