Ruby ternary operator without else Ruby ternary operator without else ruby ruby

Ruby ternary operator without else


As a general rule: you pretty much never need the ternary operator in Ruby. The reason why you need it in C, is because in C if is a statement, so if you want to return a value you have to use the ternary operator, which is an expression.

In Ruby, everything is an expression, there are no statements, which makes the ternary operator pretty much superfluous. You can always replace

cond ? then_branch : else_branch

with

if cond then then_branch else else_branch end

So, in your example:

object.method ? a.action : nil

is equivalent to

if object.method then a.action end

which as @Greg Campbell points out is in turn equivalent to the trailing if modifier form

a.action if object.method

Also, since the boolean operators in Ruby not just return true or false, but the value of the last evaluated expression, you can use them for control flow. This is an idiom imported from Perl, and would look like this:

object.method and a.action


Greg's answer is the best, but for the record, and even more than in C, expressions and statements are equivalent in Ruby, so besides a.action if o.m? you can also do things like:

object.method? && a.action

You can write (a; b; c) if d or even

(a b c) if d

or for that matter: (x; y; z) ? (a; b c) : (d; e; f)

There is no situation in Ruby where only a single statement or expression is allowed...