Run a business? Check out LessAccounting, our bookkeeping system that'll save you hours per week.

Announcing:

We built the entrepreneur's bookkeeping system, it's called LessAccounting. You'll probably love it.

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.

5 Comments

Yardboy
Yardboy said on December 16, 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.

Randy Schmidt
Randy Schmidt said on December 16, 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!

Eugen
Eugen said on December 16, 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 :)

Steven Bristol
Steven Bristol said on December 16, 2008

I added an example.

Josh Nichols
Josh Nichols said on December 16, 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.

About Steven
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.

You Should...

Follow Steven on Twitter
Friend Steven on Facebook
Subscribe
LessEverything Copyright 2011 LessEverything.com
We don't like footers, they're kinda boring