DEV Community

Cover image for Using Case Statements
Jessica Triana
Jessica Triana

Posted on • Edited on

Using Case Statements

As a true beginner, every line of code is a learning opportunity.

This week, I paired with another student and successfully completed our first-ever CLI program as part of our curriculum at Flatiron School. We implemented many of the skills that we learned in just 2 weeks of the program including: OOP, Ruby, SQL and ActiveRecord.

Just when I thought I had leveled up and written the perfect block of code in our “Main Menu”, my teammate slacked me with a question. He asked if I considered using a case statement in place of my many “If…else…” lines of code. Honestly, this never crossed my mind. I was familiar with the terminology but didn’t realize it would be much easier and “cleaner” to refractor this block of code.

In short: A case statement starts out with an optional condition accompanied with a number of “when” clauses. The first “when” clause to evaluate to true is executed.

A simple case statement example:
Alt Text

In the Main Menu of our CLI program, each "when" clause executes a method that helps the user navigate the program:
Alt Text

The user only sees the following text:
Alt Text

Typically, case statements are a better choice over "If...else..." conditional statements when you have 3 or more conditions to evaluate.

You can also write a case statement with multiple "when" clauses, separated by commas:
Alt Text

Personally, this was a short but valuable lesson in refactoring code that I was able to implement in multiple parts of our program! There are many creative uses of case statements beyond these examples.

Visit www.ruby-doc.org to learn more.

Top comments (0)