如何switch
在Ruby中编写语句?
Ruby使用case
表达式代替。
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
没有落空,所以没有必要结束每when
一个break
。您还可以在单个when
子句中指定多个匹配项,例如when "foo", "bar"
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句