Ternary Operator

Learn about ternary operators and how to use them in Ruby.

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()

This is 100% the same as the following code, but with the inclusion of if...else:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy