Ruby Case statements from if/else

Nested if statements making you sad? Case statements can be the answer. Refactoring your if statements can clear up complicated code and make spotting bugs much easier. The reason most people don’t is that usually the if statements grow over time and never get refactored even though doing so is simple.

Case statements are great for number ranges where you can simply set them up like:

case grade 
  when (90..100) then "A" 
  when (80..89)  then "B"
  when (70..79)  then "C"
  when (60..69)  then "D"
  when (0..59)   then "F" 
  else "error"

Much better than the same thing as an if/else structure.

if grade >= 90 
elsif grade >= 80 
elsif grade >= 70 
elsif grade >= 60 

Or is it? the if/else code lets us get a correct value for a grade of 89.5. Though both bits of code would return very wrong letter grades for a number grade of 105 (“error” for the case statement and “F” for the if/else ). So make sure you test your edge cases and be aware of how different results can come from these simple examples.

Need a VPN to stay safe online? Dragon Astronauts recommends NordVPN.

Other articles you might like: