Ruby Ternary Operator

March 9, 2021  ‐ 1 min read

The ternary operator in Ruby is a C-style conditional expression that allows you to quickly define a conditional.

You only need one line and it comes in handy when you need to do a variable assignment based on a condition.

The expression takes the form of: <condition> ? <value if true> : <value if false>.

Let's for example say that we want to assign the name of a bird based on the trait that it flies.

Instead of writing an if/else like this.

name = if bird.can_fly
         'Pidgin'
       else
         'Ostrich'
       end

You can write it as follows with the ternary operator.

name = bird.can_fly ? 'Pidgin' : 'Ostrich'

Nested Ternary Operator

If you want to go crazy you can nest a ternary operator as well, since it's just an expression.

name = bird.can_fly ? 'Pidgin' : (bird.can_swin ? 'Penguin' : 'Ostrich')