The Ternary Operator

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

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.

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Learn To Code Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat