Syed Humza Shah


Engineering leader. Likes coffee. Loves to travel. Runs on a combination of optimism and pragmatism.

Read more about him here.

Ruby's Shortcut-boolean and bitwise-boolean assignment operators

You are probably familiar with the shortcut-OR-assignment operator i.e. ||=. Basically, c ||= b is just a shortcut for the following:

c = c || b
# i.e. if c is nil or false, assign b's value to c

While that operator is used extensively, there are similar operators that not as many Rubyists and Railsers (Railsists?) know about.

Let’s start with one that is very similar to the abovementioned operator: &&=

It does exactly what you would expect it to:

b = true
b &&= false
b #=> false

Just like ||=, &&= isn’t restricted to true and false.

b = 4
b &&= {}
b #=> {}

As you might (should) already know, the || and && operators are called “shortcut” OR and AND respectively whereas the | and & operators are called bitwise OR and AND respectively. There are bitwise-equivalents to the ||= and &&= operators too!

b = 4
c = 8
b |= c
b #=> 12 i.e. 0100 OR'ed with 1000 => 1100
b = 4
b &= c
b #=> 0 i.e. 0100 AND'ed with 1000 => 0000

Admiteddly, ||= is the one with the most use-cases. But it’s beneficial to have these others stored in the back of your mind. You never know when you stumble upon a code situation like this:

user_hash[:status] = user_hash[:status] && (user_hash[:end_date] ==

Which can easily be shortened via:

user_hash[:status] &&= (user_hash[:end_date] ==