如何在Ruby中编写switch语句 [英] How to write a switch statement in Ruby
问题描述
如何在Ruby中编写 switch
语句?
How do I write a switch
statement in Ruby?
推荐答案
Ruby使用 case
表达式。
Ruby uses the case
expression instead.
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在时比较对象
子句,并使用 ===
运算符将对象放在 case
子句中。例如, 1..5 === x
,而不是 x === 1..5
。
Ruby compares the object in the when
clause with the object in the case
clause using the ===
operator. For example, 1..5 === x
, and not x === 1..5
.
如上所述,这允许使用复杂的子句
。可以测试范围,类和各种各样的东西,而不仅仅是相等性。
This allows for sophisticated when
clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.
与 switch
语句不同其他语言,Ruby的案例
没有 fall- ,因此无需在每个结束时以
终止
。您还可以在单个 when
子句中指定多个匹配项,例如 when, foo, bar
时。
Unlike switch
statements in many other languages, Ruby’s case
does not have fall-through, so there is no need to end each when
with a break
. You can also specify multiple matches in a single when
clause like when "foo", "bar"
.
这篇关于如何在Ruby中编写switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!