如何在Ruby中编写switch语句?


当前回答

它被称为case,它的工作方式与您预期的一样,加上实现测试的==提供的更多有趣的东西。

case 5
  when 5
    puts 'yes'
  else
    puts 'else'
end

现在来点乐趣吧:

case 5 # every selector below would fire (if first)
  when 3..7    # OK, this is nice
  when 3,4,5,6 # also nice
  when Fixnum  # or
  when Integer # or
  when Numeric # or
  when Comparable # (?!) or
  when Object  # (duhh) or
  when Kernel  # (?!) or
  when BasicObject # (enough already)
    ...
end

事实证明,你也可以用case替换任意的if/else链(也就是说,即使测试不涉及公共变量),方法是省去初始case参数,只编写第一个匹配的表达式。

case
  when x.nil?
    ...
  when (x.match /'^fn'/)
    ...
  when (x.include? 'substring')
    ...
  when x.gsub('o', 'z') == 'fnzrq'
    ...
  when Time.now.tuesday?
    ...
end

其他回答

可以使用正则表达式,例如查找字符串类型:

case foo
when /^(true|false)$/
   puts "Given string is boolean"
when /^[0-9]+$/ 
   puts "Given string is integer"
when /^[0-9\.]+$/
   puts "Given string is float"
else
   puts "Given string is probably string"
end

Ruby的情况将使用相等操作数==(感谢@JimDeville)。更多信息请访问“Ruby Operators”。这也可以使用@mmdemirbas示例(不带参数)来完成,只有这种方法对于这些类型的情况更干净。

$age =  5
case $age
when 0 .. 2
   puts "baby"
when 3 .. 6
   puts "little child"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "youth"
else
   puts "adult"
end

有关更多信息,请参阅“Ruby-if…else,case,除非”。

我更喜欢使用case+then

number = 10

case number
when 1...8 then # ...
when 8...15 then # ...
when 15.. then # ...
end

案例什么时候

为Chuck的答案添加更多示例:

使用参数:

case a
when 1
  puts "Single value"
when 2, 3
  puts "One of comma-separated values"
when 4..6
  puts "One of 4, 5, 6"
when 7...9
  puts "One of 7, 8, but not 9"
else
  puts "Any other thing"
end

无参数:

case
when b < 3
  puts "Little than 3"
when b == 3
  puts "Equal to 3"
when (1..10) === b
  puts "Something in closed range of [1..10]"
end

请注意kikito警告的“如何在Ruby中编写switch语句”。

正如上面的许多答案中所述,在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中是一个真值。我们很快就会回来讨论这个问题。