Ruby: Case Statements and the Ternary Operator
In looking at some basic conditionals we discovered some super cool syntax that Ruby uses to shorten large blocks of conditional code. Ruby has more tricks up its sleeve, and those tricks come in the form of the case statement and the ternary operator.
The Case Statement
If we have a conditional statement that has a lot of possible cases, the case statement is the way to go. If looks like this:
As you can see the case statement allows us to not write language ==
in every condition over and over. But guess what! Even that is too long! And Ruby let’s us write it like this instead:
The Ternary Operator
The ternary operator is a good option for an if/else statement that only has two cases, that is one option if the case is true and one option if the case is false. It looks like this:
boolean ? do this is boolean is true : do this if boolean is false
For instance:
13 < 7 ? "13 is greater than 7!" : "That's not right..."
would output "That's not right..."
because 13 < 7
is false