Guarded Assignment in Ruby

Written by on Dec 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.

Meet
Steven

Hi I'm Steven,

I wrote the article you're reading... I lead the developers, write music, used to race motorcycles, and help clients find the right features to build on their product.

Get Blog Updates