The Ruby Case statement differs slightly from other languages, and for some reason it is something I always have trouble remembering the exact syntax for.
case n
when 0 then
puts 'Nothing'
when 2, 7, 10 then
puts 'Other Numbers'
else
puts 'There is nothing here'
end
Another example:
Lets say we have a variable called name we are switching on (ie depending on what value the variable holds will determine the outcome of the case statement).
case name
when "Jason" then
puts "Hello Jason you are a valued customer, welcome back."
when "Peter" then
puts "Hello Peter very nice to have you back"
when "Paul" then
puts "Hello Paul, we haven't seen you here in ages!"
else
puts "Hello stranger, welcome!"
end
If the variable name is set to "Jason" before the case statement is executed, then the text: "Hello Jason you are a valued customer, welcome back." will be displayed on STDOut. If set to "Peter" then STDOut will show "Hello Peter very nice to have you back", if set to "Paul" then it will display "Hello Paul, we haven't seen you here in ages!", and if set to anything but these three strings, "Hello stranger, welcome!" will be displayed.
Don’t forget, string comparaisons are case sensitive, so "Peter", "peter", "pEtEr" and "PeTeR" are all different and will not match! (Unless of course you downcase or upcase everything!)