43
有人可以提供一個關於如何在Ruby中爲變量使用switch case的例子嗎?Ruby on Rails Switch
有人可以提供一個關於如何在Ruby中爲變量使用switch case的例子嗎?Ruby on Rails Switch
我假設你指的是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}"
非常感謝。我可以用params [:id]替換a_variable嗎? – glarkou
當然,只要確保比較相同類型的變量,例如「1」不等於1.但是「1」.to_i等於1(to_i將字符串轉換爲整數)。如果您想將params [:id]與一個整數進行比較,您需要執行「case params [:id] .to_i」。用「case」測試params [:id]對我來說看起來有點奇怪,你確定你在做什麼? –
謝謝隊友。這真的很有幫助。我認爲那是問題! – glarkou