Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

ruby - 如何在Ruby中编写switch语句(How to write a switch statement in Ruby)

如何在Ruby中编写switch语句?

  ask by Readonly translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ruby uses the case expression instead.

(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 compares the object in the when clause with the object in the case clause using the === operator.

(Ruby使用===运算符将when子句中的对象与case子句中的对象进行比较。)

For example, 1..5 === x , and not x === 1..5 .

(例如, 1..5 === x ,而不是x === 1..5 。)

This allows for sophisticated when clauses as seen above.

(如上所述,这可以实现复杂的when子句。)

Ranges, classes and all sorts of things can be tested for rather than just equality.

(可以测试范围,类和各种各样的东西,而不仅仅是相等性。)

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 .

(不像switch在许多其他语言的语句,Ruby的case并没有落空 ,所以没有必要每次结束whenbreak 。)

You can also specify multiple matches in a single when clause like when "foo", "bar" .

(您还可以在单??个when子句中指定多个匹配项,例如when "foo", "bar" 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...