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

Ruby has the ternary operator:

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

But it also has something else…

1 a = (true  && 'a') || b #=> "a"
2 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.

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

Does anyone else see it?