Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 15 / 68

The Ternary Operator

In this lesson you will learn Ruby's ternary operator so you can express a simple branch concisely on one line. This is for anyone searching for "Ruby ternary operator how to use".

condition ? valueIfTrue : valueIfFalse expresses a simple if statement on one line. It suits short decisions such as working out whether someone counts as an adult and picking a message on the spot.

The sample code uses age >= 20 ? "Adult" : "Minor" to choose which string to assign to message based on age. Notice how one line replaces what would take several with an if statement.

A common stumbling block for beginners is nesting ternary operators until they become unreadable. Cramming a complex condition in makes things worse, so the trick is to reserve it for simple either/or decisions.

The ternary operator is often paired with an assignment and helps keep code compact. Ruby also offers the trailing if as an alternative, so you pick whichever reads better in the situation.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)