Allan & Steve are the chubby founders of LessEverything. This is their blog, hear them rant, praise, give advice and talk about Just Stuff, Less Accounting, Lovd by Less, More Honey, Events, Less Memories, Code, Business, Design, Marketing

Guarded Assignment in Ruby

written by Steven Bristol on December 16th, 2008

Most people familiar with Ruby are familiar with the Ruby operator ||=. What it does is assign the value of the right to the variable on the left if left is nil (or false). Here is an example:

Most people however are not familiar with the corollary operator &&=. What it does is assign the value of the right to the variable on the left if left is not nil (or false). Here is an example:

Here is an example of how one might use &&=. The idea is that you have an array of something and you only really care if they all completed or not. I used AR::Base.save to show a poor man’s transactions.

5 Responses to “Guarded Assignment in Ruby”

  1. Yardboy December 16th, 2008

    Ow, my head! You are correct, I’d never thought there was a corollary to ||=. Examples of where this might be useful are escaping me at the moment, but thanks.

  2. Randy Schmidt December 16th, 2008

    I saw this a couple of weeks ago and didn’t know what it was… I also couldn’t figure out how to google for what it was. So… thanks!

  3. Eugen December 16th, 2008

    Can anyone show me a small example where this might come in handy?

    I didn’t know of it, but it seems kind of nifty. Thanks for yet another ruby tip to make my code less readable to others. Yay :)

  4. Steven Bristol December 16th, 2008

    I added an example.

  5. Josh Nichols December 16th, 2008

    Yeah, finding good places to use &&= can be tricky.

    One way I’ll often use it is for string manipulation.

    foo &&= foo.squeeze

    If you end up doing more than one of these in a row, you’d probably want to make it an if block.

Sorry, comments are closed for this article.