The Ruby Ternary Operator

What is a ternary operator in Ruby?

A ternary operator is made of three parts. These parts include a conditional statement & two possible outcomes. A ternary gives you a way to write a compact if/else expression in just one line of code.

For example:

if mango_stock > 1
"eat_mango"
else
"buy_mango"
end

Using ternary operator, we can shorten this code to the following:

mango_stock > 1 ? “eat_mango” : “buy_mango”

Follow this template below for writing your own ternary operator.

condition ? true : false

The first part of the ternary operator is the condition, as in the condition you want to check if it’s true or not. After that, we have a question mark (?).

Next:

We write whatever code you want to run if the condition turns out to be true, the first possible outcome. Then a colon(:), another syntax element. Lastly, we write the code you want to run if the condition is false.

Ternary operation is a generalized way of expressing simple conditionals in computer science. If you have more than three items, it’s better to default back to an if statement. The ternary conditional operator allows you to write compact conditional statements which make your code easier to read. Always practice what you learn, to become better at using it.

Full Stack Software Engineer