如何在 Ruby 中编写 switch 语句 [英] How to write a switch statement in Ruby

查看:40
本文介绍了如何在 Ruby 中编写 switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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 使用 === 运算符将 when 子句中的对象与 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.

这允许复杂的 when 子句,如上所示.可以测试范围、类和各种事物,而不仅仅是相等性.

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 的 case 没有 fall-through,所以不需要用 break 结束每个 when.您还可以在单​​个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆