Guarded Assignment in Ruby
written by Steven on December 16, 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.
Business Owners: save hours per week with
LessAccounting. It's like Quickbooks, just not total shit.
Leave a Comment
About Steven
Popular Articles
Subscribe

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.

5 Comments
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.
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!
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 :)
I added an example.
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.