This may be a well-know Ruby trick, but I thought I’d share it anyway.

Ruby has the ternary operator:

a = true  ? 'a' : 'b' #=> "a"
b = false ? 'a' : 'b' #=> "b"

But it also has something else…

a = (true  && 'a') || b #=> "a"
b = (false && 'a') || b #=> "b"

All statements in Ruby return the value of the last expression evaluated, so true && 'a' returns ‘a’, and the ‘b’ is ignored (via boolean short-circuiting). false && 'a' evaluates to false, so Ruby moves on, and returns ‘b’.


This is a lot like the a ||= 'a' trick, which expands to a = a || 'a', giving the variable a default value, if it’s not already initialized.

If Ruby already has the ternary operator, why bother? Personally, I find this form more natural (which surprised me, after years of using the ternary operator in Java and C#). For some reason, it reads more like natural language to me.

user_name = (user.authenticated? && || 'guest'

Does anyone else see it?