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:

irb(main):001:0> a, b = nil, 2
=> [nil, 2]
irb(main):002:0> b ||= a
=> 2
irb(main):003:0> b
=> 2
irb(main):004:0> a
=> nil
irb(main):005:0> a ||= b
=> 2
irb(main):006:0> b
=> 2
irb(main):007:0> a
=> 2

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:

irb(main):001:0> a, b = nil, 2
=> [nil, 2]
irb(main):002:0> a &&= b
=> nil
irb(main):003:0> a = 1
=> 1
irb(main):004:0> a &&= b
=> 2
irb(main):005:0> a
=> 2
irb(main):006:0> b
=> 2

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.

class Object
  def save
    rand > 0.5
  end
end

array_of_unsaved_active_record_objects = []
1.upto(10) { |i| array_of_unsaved_active_record_objects << i}

all_saved = true
array_of_unsaved_active_record_objects.each do |ar|
  x = ar.save
  puts "#{ar} saved?: #{x}"
  all_saved &&= x
end

puts "They all saved: #{all_saved}"



1 saved?: true
2 saved?: false
3 saved?: false
4 saved?: true
5 saved?: false
6 saved?: false
7 saved?: false
8 saved?: false
9 saved?: true
10 saved?: false
They all saved: false
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