Ruby on Rails Switch

Ruby on Rails Switch

本问题已经有最佳答案,请猛点这里访问。

有人能提供一个关于如何使用ruby中的switch case for variable的例子吗?


我想你指的是案例/时间。

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
puts case a_variable
when 1
 "it was 1"
when 2
 "it was 2"
else
 "it was something else"
end

编辑

可能不是每个人都知道,但非常有用的是,您可以在case语句中使用regexps。

1
2
3
4
5
6
7
8
9
10
11
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}"