Switch Statments in Ruby compared to PHP
Yup, you’re in luck, case statements (a.k.a. switch statements) are pretttty much the same across the board from PHP to Ruby too.
Here’s a familiar PHP example:
But they call them “case statements” in Ruby-land:
case number
when 0
puts '0 is a cool number'
when 1
puts 'Dylan really needs to think up better examples'
else
puts 'What do you expect of me? I am just a 2 trick pony.'
end
Ruby again wins in the less-keystrokes category. 2 major differences:
break
is implied. The bad practice of having multiple results from 1 case isn’t possible in Ruby. So no more doh! moments when you forget to add break’s in your code.- The result is again storable in a variable. Which. is. awesome.
To demonstrate major difference #2 - an example:
number = 1
result = case number
when 0
'0 is a cool number'
when 1
'Dylan really needs to think up better examples'
else
'What do you expect of me? I am just a 2 trick pony.'
end
puts result
=> 'Dylan really needs to think up better examples'
Amazing! For that same result in PHP we’d have to meticously define the same variable in each of the valid cases, or define the variable outside of the scope of the switch statement:
Again the difference is so small in terms of the number of keystrokes, but the possiblities of shooting yourself in the foot have been greatly diminished.