【发布时间】:2011-09-30 00:12:34
【问题描述】:
谁能提供一个例子来说明如何在 Ruby 中使用 switch case 来处理变量?
【问题讨论】:
标签: ruby switch-statement
谁能提供一个例子来说明如何在 Ruby 中使用 switch case 来处理变量?
【问题讨论】:
标签: ruby switch-statement
我假设您指的是案例/何时。
case a_variable # a_variable is the variable we want to compare
when 1 #compare to 1
puts "it was 1"
when 2 #compare to 2
puts "it was 2"
else
puts "it was something else"
end
或
puts case a_variable
when 1
"it was 1"
when 2
"it was 2"
else
"it was something else"
end
编辑
也许不是每个人都知道,但非常有用的是您可以在 case 语句中使用正则表达式。
foo = "1Aheppsdf"
what = case foo
when /^[0-9]/
"Begins with a number"
when /^[a-zA-Z]/
"Begins with a letter"
else
"Begins with something else"
end
puts "String: #{what}"
【讨论】:
when 中列出多个(逗号分隔)项目。最后,它们不仅匹配相等,还匹配 === 运算符,因此:String === "thing" 为真,因此 when String then whatever 将匹配。
switch 语句不同,Ruby 的case 没有fall-through,因此无需以when 结尾break.