Ternary Statements in Ruby

Mikel Bishop
2 min readDec 18, 2021

Ternary operators seemed complex when I first learned them. I was hesitant to use them as I couldn’t remember the syntax and the one liner just was confusing. Then one day, someone who was reviewing one of my projects and providing feedback on a bug I was working on sent me part of my own code — rewritten as a ternary. All of a sudden, it made sense.

When and why use ternaries? Ternary operators are a good choice to replace if/else statements (but not if there is an elsif). This is a compact way to reduce 5 lines into one. It can make your code look a bit cleaner and more concise.

Syntax:

Let’s break it down a bit — from left to right:

  • We start with the condition.
  • “?” is the ternary operator.
  • action_if_true
  • “:” acts like “else”
  • action_if_false

Let’s take a look at an example:

If ternary statements looked complicated to you as well, I hope this is a helpful way of looking at them.

--

--