Ruby ❤ Shorthand: Ternary Operators
The very first thing I caught on to as a new developer was the hotly debated if else statement. It’s simple and makes total sense — if “this” is true do this thing, “else” do this thing. It’s kind of like how I answer the phone. If I know the number that’s calling me, I answer; else I let that baby go to voicemail.
Of course, this method could be written a couple of different ways, depending on the logic of your code:
if number.known?
answer_the_phone
else
voicemail
end
unless number.known?
voicemail
else
answer_the_phone
end
number.known? ? answer_the_phone : voicemail
Wait… what’s that last one?
The beauty (and sometimes, downfall) of Ruby is that there are many different ways to write the same logic. While if else statements (and unless statements) are really clear and easy to read, they’re not very concise. When you’re digging through hundreds upon thousands of lines of code, seeing “if else if else if else” can get repetitive and is often unnecessary, not to mention it takes up a lot of room. My simple example was condensed into one line from five using a ternary operator.
Just like how doctors come up with illegible shorthand for things they write all the time, so do developers. If you’re not in the know, “ternary” means “composed of three items.” Your three items are the object you’re performing the method on, what happens if the object evaluates to true, and what happens in any other case.
object ? do_thing : do_other_thing
Another example:
kitten.cute? ? adopt_immediately : buy_swanky_collar_after_adopting_immediately
Using the ternary operator is a handy little trick that will take you from noob to a little less of a noob. I see these used all throughout the codebase at my job, and got a very polite slap on the wrist the first time I tried to use an if else statement in a ticket when I could have used a ternary operator. (My very first ticket, but everyone can use a little help with improvement.) There are definitely still if else statements that exist, but they’re used for more complicated statements that include multiple if’s. If you have more than three items, it’s better to default back to an if statement.
if cat.age_in_months < 1
kitten
if cat.age => 10
senior_cat
if cat.age => 1 && > 10
adult
else
age_unknown
end
Don’t sacrifice readability for cleverness — it’s much better for someone to be able to read your code than to struggle to figure out what it means. They’re more likely to think, “This is obnoxious” than “This is super cool.” And when it comes to sharing code, no one is having a good time if they don’t know what you’re trying to say. Onward!