开发者

Ruby on Rails Switch [duplicate]

This question already has answers here: 开发者_高级运维 How to write a switch statement in Ruby (28 answers) Closed 9 years ago.

Can someone provide an example on how to use switch case in Ruby for variable?


I assume you refer to 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

or

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

EDIT

Something that maybe not everyone knows about but what can be very useful is that you can use regexps in a case statement.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜