如何在Ruby中编写switch语句?


当前回答

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子句中指定多个匹配项,如when“foo”、“bar”。

其他回答

我已经开始使用:

a = "secondcase"

var_name = case a
  when "firstcase" then "foo"
  when "secondcase" then "bar"
end

puts var_name
>> "bar"

在某些情况下,它有助于压缩代码。

正如上面的许多答案中所述,在case/when语句中,==运算符是在引擎盖下使用的。

以下是有关该操作员的附加信息:

大小写相等运算符:===

Ruby的许多内置类,如String、Range和Regexp,都提供了自己的==运算符实现,也称为“大小写相等”、“三重相等”或“三个相等”。因为它在每个类中的实现方式不同,所以它的行为会因调用对象的类型而异。通常,如果右边的对象“属于”或“是”左边对象的成员,则返回true。例如,它可以用于测试对象是否是类(或其子类之一)的实例。

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

同样的结果可以用其他可能最适合这项工作的方法实现,例如is_a?和instance_of?。

范围实施===

当对范围对象调用==运算符时,如果右侧的值位于左侧的范围内,则返回true。

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

请记住,==运算符调用左侧对象的==方法。所以(1..4)==3等于(1..4==3。换句话说,左侧操作数的类将定义将调用==方法的哪个实现,因此操作数位置不可互换。

Regexp的实现===

如果右侧的字符串与左侧的正则表达式匹配,则返回true。

/zen/ === "practice zazen today"  # Output: => true
# is similar to
"practice zazen today"=~ /zen/

上面两个示例之间唯一相关的区别是,当存在匹配时,==返回true,而==返回整数,这在Ruby中是一个真值。我们很快就会回来讨论这个问题。

case语句运算符在其他语言中类似于switch。

这是switch的语法。。。C中的情况:

switch (expression)
​{
    case constant1:
      // statements
      break;
    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

这是case的语法。。。使用Ruby时:

case expression
  when constant1, constant2 #Each when statement can have multiple candidate values, separated by commas.
     # statements 
     next # is like continue in other languages
  when constant3
     # statements 
     exit # exit is like break in other languages
  .
  .
  .
  else
     # statements
end

例如:

x = 10
case x
when 1,2,3
  puts "1, 2, or 3"
  exit
when 10
  puts "10" # it will stop here and execute that line
  exit # then it'll exit
else
  puts "Some other number"
end

有关更多信息,请参阅案例文档。

许多编程语言,特别是源于C的语言,都支持所谓的Switch Fallthrough。我正在寻找在Ruby中实现这一点的最佳方法,并认为这可能对其他人有用:

在类C语言中,故障通常如下所示:

switch (expression) {
    case 'a':
    case 'b':
    case 'c':
        // Do something for a, b or c
        break;
    case 'd':
    case 'e':
        // Do something else for d or e
        break;
}

在Ruby中,同样可以通过以下方式实现:

case expression
when 'a', 'b', 'c'
  # Do something for a, b or c
when 'd', 'e'
  # Do something else for d or e
end

这并不是严格等价的,因为不可能让“a”在变成“b”或“c”之前执行一块代码,但在大多数情况下,我发现它足够相似,以同样的方式有用。

这是在Ruby中使用case完成的。另请参阅维基百科上的“Switch语句”。

引用:

case n
when 0
  puts 'You typed zero'
when 1, 9
  puts 'n is a perfect square'
when 2
  puts 'n is a prime number'
  puts 'n is an even number'
when 3, 5, 7
  puts 'n is a prime number'
when 4, 6, 8
  puts 'n is an even number'
else
  puts 'Only single-digit numbers are allowed'
end

另一个例子:

score = 70

result = case score
   when 0..40 then "Fail"
   when 41..60 then "Pass"
   when 61..70 then "Pass with Merit"
   when 71..100 then "Pass with Distinction"
   else "Invalid Score"
end

puts result

在我的Kindle上的《Ruby编程语言》(第一版,O'Reilly)第123页左右,它说when子句后面的then关键字可以用换行符或分号替换(就像if-then-else语法中的那样)。(Ruby 1.8也允许用冒号代替then,但Ruby 1.9中不再允许使用这种语法。)