Case Statements

I am continuing along on learning Ruby. Today, it’s a dive into case statements!

So, case statements are used to run multiple conditions against one value. To create a case statements you need:

  1. a value
  2. one or more conditions to compare the value to
  3. code to run if the condition is met

Case statements are useful when you have have a list of possible conditions and you need your code to operate if the condition is met. Consider this:

I mean, the above works but it is needlessly complex. Flatiron called it “code smell,” a phrase I am completely unfamiliar with but makes sense. We can do this better with a case statement. Let’s take a look:

So, let’s examine what we did! First we create the value we are testing

Then adding in conditions:

In the above, the name passed in will be tested against the condition and then, in this last part, if it meets it it will execute that code.

And, as seen above, we can add an else at the end that will run when no case value is met!