如何在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”。

其他回答

Ruby在2.7中引入了模式匹配

这是一个超级强大的功能

它也使用case,但有另一种语法

还有查找模式功能

users =
  { users:
    [
      { user: 'user', email: 'user@user.com' },
      { user: 'admin', email: 'admin@admin.com' },
    ]
  }

case users
in users: [*, { user:, email: /admin/ => admin_email }, *]
  puts admin_email
else
  puts "No admin"
end

# will print admin@admin.com

与通常情况不同,如果条件不匹配,将抛出NoMatchingPatternError。所以你可能不得不使用else分支

案例当处理类时,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

我今天在寻找答案的时候遇到了这个问题,这是第一个出现的页面,所以我认为这对其他处于同样情况的人来说很有用。

puts "Recommend me a language to learn?"
input = gets.chomp.downcase.to_s

case input
when 'ruby'
    puts "Learn Ruby"
when 'python'
    puts "Learn Python"
when 'java'
    puts "Learn Java"
when 'php'
    puts "Learn PHP"
else
    "Go to Sleep!"
end

这是在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中不再允许使用这种语法。)

很多很好的答案,但我想我会补充一个事实。。如果您试图比较对象(类),请确保您有一个太空船方法(不是玩笑)或了解它们是如何比较的

“Ruby平等和对象比较”是一个很好的话题讨论。