← Back to Ruby Operators

Ternary Operator

The ternary operator syntax is a conditional syntax that makes use of the ? and : symbols. Don't need a multi-line if/else, then maybe the ternary operator is right for you.

> User = Struct.new(:veg)
=> User
> user = User.new(veg: true)
=> #<struct User veg={:veg=>true}>
> meal = user.veg ? 'Risotto' : 'Chicken'
=> "Risotto"

Be careful to not overcomplicate logic with a ternary when boolean logic will do:

> name = 'Matz'
=> "Matz"
> who = name ? name : 'World'
=> "Matz"
> puts "Hello, #{who}!"
Hello, Matz!
=> nil

We are better off with a boolean or in this case:

> who = name || 'World'
=> "Matz"
> puts "Hello, #{who}!"
Hello, Matz!
=> nil

References