Search⌘ K

Ternary Operator

Explore the use of the ternary operator in Ruby to write compact conditional statements. Understand its syntax, practical examples, and when to prefer it over traditional if...else structures. This lesson helps you write clearer and shorter code by using ternary expressions effectively.

We'll cover the following...

Use of ternary operators

The ternary operator is a useful feature in any language. It’s implemented in Ruby the same way that it is implemented in C, Java, Python, JavaScript, and so on. Some programmers have been using this operator for a long time, but aren’t familiar with its name. But we recommend remembering its name, because it’s always nice to use the correct names and terminology.

Despite the intimidating name, its syntax is quite straightforward:

something_is_truthy ? do_this() : else_this()

For example:

is_it_raining? ? stay_home() : go_party()
...