2011-07-06 232 views

回答

90

我假设你指的是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 

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}" 
+0

非常感谢。我可以用params [:id]替换a_variable吗? – glarkou

+0

当然,只要确保比较相同类型的变量,例如“1”不等于1.但是“1”.to_i等于1(to_i将字符串转换为整数)。如果您想将params [:id]与一个整数进行比较,您需要执行“case params [:id] .to_i”。用“case”测试params [:id]对我来说看起来有点奇怪,你确定你在做什么? –

+0

谢谢队友。这真的很有帮助。我认为那是问题! – glarkou