In Case You Missed It

In all my time programming, I’ve never really used the “case” statement until yesterday. I was working on the following problem:

Write a program with a “smiley” method that accepts a hash as an argument. If the hash element with the key :mood has the value “happy”, then return”:)”. If it has the value “sad”, return “:(“. Otherwise, return “:|”.

Here are the solutions using the If vs Case statement:


The typical “if” statement solution:


def smiley(hash = {})
    mood = hash[:mood]
    if mood == "happy"
      ":)"
    elsif mood == "sad"
      ":("
    else
      ":|"
    end
end

Now here is the solution to the same problem using the “case” statement:

def smiley(hash = {})
    case hash[:mood]
    when "happy"
        ":)"
    when "sad"
        ":("
    else
        ":|"
    end
end

As you can see, the case statement is a bit more intuitive to read and it takes out the constant repetition of the “mood ==” in the if statement.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.