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.
Typically, case statements are a better choice over "If...else..." conditional statements when you have 3 or more conditions to evaluate.
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.