Ruby on Rails Switch

gla*_*kou 61 ruby switch-statement

有人可以举例说明如何在Ruby中使用switch case作为变量吗?

Bjö*_*son 115

我假设您参考案例/何时.

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
Run Code Online (Sandbox Code Playgroud)

要么

puts case a_variable
when 1
  "it was 1"
when 2
  "it was 2"
else
  "it was something else"
end
Run Code Online (Sandbox Code Playgroud)

编辑

可能不是每个人都知道的东西,但是非常有用的是你可以在case语句中使用regexp.

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}"
Run Code Online (Sandbox Code Playgroud)