Development Journal

Student at Flatiron School NYC

The Ternary Operator

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:

1
Condition ? Return if true : Return if false

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Person
  attr_accessor :age

  def initialize(age)
    @age = age
  end

  def is_a_teenager?
    age.between?(13,19) ? true : false
  end

end

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

1
2
3
4
5
6
7
def teen(age)
  if age.between?(13,19)
    true
  else
    false
  end
end

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 assigment. In this case, the return of the expression would be the assigned value.

1
variable = conditional ? value_if_true  : value_if_false

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