Ruby Ternary Operations

Ruby’s other Ternary Operator

Best Practices


One comment on “Ruby Ternary Operations

  1. Maybe I’ve just been using the ternary operator so long that I don’t see the problem. But really it is a very terse way to describe a conditionally returned value. Although I agree that with ruby’s ‘?’ syntax you end up having things like

    user.is_logged_in? ? user.username : “anonymous”

    (The two question marks is what I’m annoyed about)

    Although for some reason I tend to use classic if/else in Ruby (and because everything in ruby returns a value this can also be used to assign a value).

    What is actually interesting is that in Ruby you can use the short-circuiting or operator (||) to basically perform null coalescence. Or in ruby speak, nil coalescence. And because of the way Ruby handles nil (and because nil evaluates to a boolean false) it is actually a really good way to do lots of things.

    So in the example above, you might rather do:

    user.username || “anonymous”

    Of course, convention would then say that you ensure username is nil when it has no value.

    The solution on the ‘Ruby’s other Ternary Operator’ page is an example in obfuscating code. IMHO I think it actually goes against the grain of what it is to write ruby code.

Leave a Reply

Your email address will not be published. Required fields are marked *