SHARE:
Uncategorized

The Ternary Operator

Flatiron School / 15 October 2013

The following is a guest post by Patrick Janson and originally appeared on his blog. Patrick is currently in the Ruby-003 class at The Flatiron School.

In this post, I wanted to take a look at a conditional that I have used many times as a beginner but as our class has moved into object oriented programming, the use cases have narrowed.

The ternary operator is a conditional that will return one value if the condition is true and another value if it is false. It is a common computer science operator in many languages and afforded to us Rubiest as well.

The ternary allows us programmers to inject a binary conditional into our code in a single line and can be a handy way to keep methods small and effective by avoiding ‘if/else’ blocks.

Some Latin

The term “ternary” is derived from the Latin term “termarius”. It is an adjective that means, “composed of three items”. In reference to the Ruby ternary operator, the three parts are the “Conditional” and the “True Return” and the “False Return”.

The format of the operator looks like this:

As you may have noticed, the logical decision tree behind the operator is the same as a general “if/else” statement. Because of this, it is true that the ternary operator is not generally needed but it is nice to know about it.

Here is a code example from earlier in our semester.

We had been asked to create a method that returned true if an object of the person class had an age value that was between 13-19.

This method could also have easily been coded as an if/else statement.

So as a curious novice, I wanted to know if the ternary had a more potent use.

variable assignment

We can use the ternary operator to quickly select between two values for assignment. In this case, the return of the expression would be the assigned value.

This is helpful so as doing this assignment in if/else block would be a bit more typing or we would need to employ a case statement.

Flatiron School Weekend Three - The Tap Method Previous Post Using the Mail Gem and LaunchD to Make a Newsletter Next Post