Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Switch [duplicate]

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

like image 734
glarkou Avatar asked Jul 06 '11 21:07

glarkou


1 Answers

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}"
like image 87
Björn Nilsson Avatar answered Oct 22 '22 21:10

Björn Nilsson