RubyonRails交换机
有人能提供一个关于如何在Ruby中为变量使用switch case的例子吗?我假设您指的是case/whenRubyonRails交换机,ruby,switch-statement,Ruby,Switch Statement,有人能提供一个关于如何在Ruby中为变量使用switch case的例子吗?我假设您指的是case/when 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 或 编辑
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
或
编辑
可能不是每个人都知道,但非常有用的是可以在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}"
谢谢。我可以用params[:id]替换一个_变量吗?当然,只要确保您正在比较相同类型的变量,例如“1”不等于1。但是“1”。to_i等于1(to_i将字符串转换为整数)。如果要将参数[:id]与整数进行比较,则需要执行“case params[:id].to_i”。我觉得用“case”测试params[:id]有点奇怪,你确定你在做什么吗?谢谢,伙计。这真的很有帮助。我想这就是问题所在!与传统的开关箱有一些不同。最值得注意的是,没有级联到下一项。另一个是,当时,您可以在每个
中列出多个(逗号分隔的)项目。最后,它们不只是在等式上匹配,它们在===
运算符上匹配,因此:String===“thing”
是真的,因此当String时,则匹配任何语句。重要提示:与许多其他语言中的switch
语句不同,Ruby的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}"