Some things I learned about case statements in Ruby

I’ve been working with case statements in Ruby, and I was having a difficult time getting it to do what I wanted.

Things I learned:

  1. Case statements that take an argument after the case (ex: case SOME_VARIABLE) can’t take logic after the when part of the statement.

    Bad:

    case thingie
    when thingie.match(/some regex/)
    # something cool happens
    end
    

    Good:

    case thingie
    when "a perfectly boring string"
    # something cool happens
    end
    
  2. Case statements that do not take an argument after the case CAN take logic after the when

    Good:

    case
    when thingie.match(/some regex/)
    # something cool happens
    end
    

Leave a Reply

Your email address will not be published. Required fields are marked *