如何在Ruby中编写switch语句?


当前回答

在您的环境中不支持正则表达式?例如,Shopify脚本编辑器(2018年4月):

[错误]:未初始化常量RegExp

一种变通方法,结合了前面在这里和这里介绍过的方法:

code = '!ADD-SUPER-BONUS!'

class StrContains
  def self.===(item)
    item.include? 'SUPER' or item.include? 'MEGA' or\
    item.include? 'MINI' or item.include? 'UBER'
  end
end

case code.upcase
when '12345PROMO', 'CODE-007', StrContains
  puts "Code #{code} is a discount code!"
when '!ADD-BONUS!'
  puts 'This is a bonus code!'
else
  puts 'Sorry, we can\'t do anything with the code you added...'
end

我在类方法语句中使用了or,因为||的优先级高于包括

如果您仍然喜欢使用||,即使在这种情况下或更可取,也可以改为使用:(item.include?“A”)||。。。。您可以在这个repl.it中测试它。

其他回答

如果您渴望知道如何在Ruby开关情况下使用OR条件:

因此,在case语句中,a相当于if语句中的||。

case car
   when 'Maruti', 'Hyundai'
      # Code here
end

请参阅“Ruby Case语句的工作原理和使用它可以做什么”。

在when子句中强调逗号(,)至关重要。它充当if语句的||,也就是说,它在when子句的分隔表达式之间进行OR比较,而不是and比较。参见以下案例陈述:

x = 3
case x
  when 3, x < 2 then 'apple'
  when 3, x > 2 then 'orange'
end
 => "apple"

x不小于2,但返回值为“apple”。为什么?因为x是3,并且由于“,”充当||,所以它不必计算表达式x<2。

您可能认为,要执行AND,可以执行以下操作,但它不起作用:

case x
  when (3 && x < 2) then 'apple'
  when (3 && x > 2) then 'orange'
end
 => nil 

它不起作用,因为(3&&x>2)的计算结果为true,Ruby获取true值,并将其与x进行比较,使用==,这是不正确的,因为x是3。

要进行&&比较,您必须将case视为if/else块:

case
  when x == 3 && x < 2 then 'apple'
  when x == 3 && x > 2 then 'orange'
end

在《Ruby编程语言》一书中,Matz表示后一种形式是简单的(而且很少使用)形式,它只是if/elsif/else的一种替代语法。然而,无论它是否不经常使用,我看不到任何其他方法可以为给定的when子句附加多个&&表达式。

它被称为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

案例当处理类时,when的行为有点意外。这是因为它使用了==运算符。

该运算符与预期的文字一起工作,但与类不同:

1 === 1           # => true
Fixnum === Fixnum # => false

这意味着如果你想做一个案子。。。当在对象的类上时,这将不起作用:

obj = 'hello'
case obj.class
when String
  print('It is a string')
when Fixnum
  print('It is a number')
else
  print('It is not a string or number')
end

将打印“它不是字符串或数字”。

幸运的是,这很容易解决。已定义==运算符,如果将其与类一起使用,并将该类的实例作为第二个操作数提供,则返回true:

Fixnum === 1 # => true

简而言之,可以通过从case obj.class中删除.class来修复上述代码:

obj = 'hello'
case obj  # was case obj.class
when String
  print('It is a string')
when Fixnum
  print('It is a number')
else
  print('It is not a string or number')
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语句”。