如何在Ruby中编写switch语句?


当前回答

我更喜欢使用case+then

number = 10

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

其他回答

在Ruby中,可以用两种不同的方式编写case表达式:

类似于一系列if语句在case旁边指定一个目标,并将每个when子句与目标进行比较。

age = 20
case 
when age >= 21
puts "display something"
when 1 == 0
puts "omg"
else
puts "default condition"
end

or:

case params[:unknown]
when /Something/ then 'Nothing'
when /Something else/ then 'I dont know'
end

Ruby支持case表达式。

类匹配:

case e = StandardError.new("testing")
when Exception then puts "error!"
else puts "ok!"
end # => error! 

多值匹配:

case 3
when 1,2,3 then puts "1..3"
when 4,5,6 then puts "4..6"
else puts "?"
end # => 1..3

Regex评估:

case "monkey"
when /mon/ then puts "banana"
else puts "?" 
end # => banana
$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,除非”。

Ruby使用case编写switch语句。

根据案例文件:

Case语句包含一个可选条件,该条件位于一个参数到case的位置,以及零个或多个when子句。与条件匹配的第一个when子句(或计算为布尔真值(如果条件为空)“wins”及其代码节执行。case语句的值是成功的when子句,如果没有这样的子句,则为nil。case语句可以以else子句结尾。当语句可以有多个候选值,用逗号分隔。

例子:

case x
when 1,2,3
  puts "1, 2, or 3"
when 10
  puts "10"
else
  puts "Some other number"
end

较短版本:

case x
when 1,2,3 then puts "1, 2, or 3"
when 10 then puts "10"
else puts "Some other number"
end

正如“Ruby的case语句-高级技术”所描述的Ruby case;

可用于范围:

case 5
when (1..10)
  puts "case statements match inclusion in a range"
end

## => "case statements match inclusion in a range"

可与Regex一起使用:

case "FOOBAR"
when /BAR$/
  puts "they can match regular expressions!"
end

## => "they can match regular expressions!"

可与Procs和Lambdas一起使用:

case 40
when -> (n) { n.to_s == "40" }
  puts "lambdas!"
end

## => "lambdas"

此外,还可以与您自己的匹配类一起使用:

class Success
  def self.===(item)
    item.status >= 200 && item.status < 300
  end
end

class Empty
  def self.===(item)
    item.response_size == 0
  end
end

case http_response
when Empty
  puts "response was empty"
when Success
  puts "response was a success"
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语句”。