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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With