Using Case Statements
Jessica Triana
Posted on February 14, 2020
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:
In the Main Menu of our CLI program, each "when" clause executes a method that helps the user navigate the program:
The user only sees the following 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:
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.
Posted on February 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.