Ruby on Rails 开关 [重复]

2024-02-28

有人可以提供一个关于如何在 Ruby 中使用 switch case 来表示变量的示例吗?


我假设你指的是案例/时间。

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

or

puts case a_variable
when 1
  "it was 1"
when 2
  "it was 2"
else
  "it was something else"
end

EDIT

也许不是每个人都知道但非常有用的是您可以在 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}"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby on Rails 开关 [重复] 的相关文章

随机推荐