The Ternary Operator

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, […]

Reading Time 1 min

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:

Blog post image: tumblr_inline_mupqzjVTcK1rtan47.png

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.

Blog post image: tumblr_inline_mupr0xmCMd1rtan47.png

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

Blog post image: tumblr_inline_mupr1iC2iS1rtan47.png

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.

Blog post image: tumblr_inline_mupr23Ldm21rtan47.png

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.

Disclaimer: The information in this blog is current as of October 15, 2013. Current policies, offerings, procedures, and programs may differ.

About Flatiron School

More articles by Flatiron School