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:

    switch($number) {
        case 0:
            echo '0 is a cool number';
            break;
        case 1:
            echo 'Dylan really needs to think up better examples';
            break;
        default:
            echo 'What do you expect of me? I am just a 2 trick pony.';
    }

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:

  1. 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.
  2. 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:

    $number = 1;
    $result = '';
    
    switch($number) {
        case 0:
            $result = '0 is a cool number';
            break;
        case 1:
            $result = 'Dylan really needs to think up better examples';
            break;
        default:
            $result = 'What do you expect of me? I am just a 2 trick pony.'
    }
    
    echo $result;
    
    => 'Dylan really needs to think up better examples'

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.