29
.
04
.
2024
30
.
08
.
2022
Ruby on Rails
Backend
Ruby
Tutorial

What does the ||= operator actually mean in Ruby?

Mateusz Woźniczka
Ruby Developer

The conditional operator in Ruby is commonly used but is also a bit misperceived. In some articles and tutorials, a||=b is translated to assign b to a if a does not have assigned value, and is illustrated by the example similar to the following one:

> a = nil
> a ||= 'foo'
=> "foo"
> b = 'bar'
=> "bar"
> b ||= 'foo'
=> "bar"

In this post, we will show that it is not exactly true, and we will search for the most accurate approximation, of what ||= really does.

But before that, let's do a summary of a few of Ruby's concepts.

Boolean values of Ruby expressions

All expressions are true or false in a logical sense, which can be illustrated with the example below:

def logical_value_of(expression)
  expression ? true : false
end

> logical_value_of('a string')
=> true
# empty string
> logical_value_of('')
=> true
> logical_value_of(0)
=> true
> logical_value_of(2+2)
=> true
> logical_value_of(false)
=> false
> logical_value_of(nil)
=> false

In Ruby, only false and nil evaluates to false. They are often described as Falsy.

Everything else evaluates to true and is described as Truthy.

Using this knowledge let's change a bit part of the first example:

> a = false
> a ||= 'foo'
=> "foo"
> b = 'bar'
> b ||= 'foo'
=> "bar"

As we can see ||= operator will change the value of a variable, if it evaluates to false.

The || operator

The || operator represents logical or, so a||b will be true if one of the variables evaluates to true. It also has quite an interesting ability, illustrated in the below examples:

def expensive_foo
  puts 'this is time-consuming'
  'foo'
end

> expensive_foo || expensive_foo
this is time-consuming
=> 'foo'

> false || expensive_foo
this is time-consuming
=> 'foo'

> true || expensive_foo
=> true

In the first example, the expensive_method has been called only once. In the last example, that method has not been called at all. It is because the second argument of the || operator is not evaluated if the first one evaluates to true - its value won't change the result anyways.

It is an example of lazy evaluation - the expression is not called when it is not needed (and in this case, it is not needed, because its value won't change anything).

As we can see, it is not returning a boolean value - instead, it is returning the first value, that evaluates to true. We can observe it in the first, and the second example, where the output is "foo".

Let's get back to our example, and update it slightly to check if lazy evaluation is also applied to the ||= operator:

def expensive_foo
  puts 'this is time-consuming'
  'foo'
end

> a = nil
=> nil
> a ||= expensive_foo
this is time-consuming
=> 'foo'
a
=> 'foo'
a ||= expensive_foo
=> 'foo'

The expensive_foo method is called only once - when a evaluates to false. Late, when a has the assigned value, the ||= operator returns the value of a without evaluating the second argument.

Approximations of ||=

The three most common approximations of a ||= b that can be found in multiple articles, or discussions are:

  • a = a || b
  • a = b unless a
  • a || a = b

Let's do some tests to check which one of them is right. To do it thoroughly we will use the following classes:

class ValueKeeper
attr_accessor :value

  def value=(input)
    puts "assigning #{input} to value"
    @value = input
  end
end

We will use it to keep our value (instead of the a variable). It will inform us, whenever a value is assigned to it.

class Operation

  def result(input)
    puts "calculating result for #{input}..."
    input
  end
end

Whenever the result method is called, we will be informed by the console message.

First, let's check how the ||= operator behaves in our example:

# "a ||= b"
> operation = Operation.new
> object = ValueKeeper.new

> object.value ||= operation.result('foo')
calculating result for foo...
assigning foo to the value
=> "foo"
> object.value ||= operation.result('bar')
=> "foo"

As expected, when object.value holds no value (and evaluates to false) Operation.result is run, and then its output is assigned to the object.value. When the command is run for the second time, we simply get the output without any calculation or assignment.

# "a = a || b"
> operation = Operation.new
> object = ValueKeeper.new

> object.value = object.value || operation.result('foo')
calculating result for foo...
assigning foo to the value
=> "foo"
> object.value = object.value || operation.result('foo')
assigning foo to the value
=> "foo"

Test results for the a = a || b approximation show that when the command was triggered for the first time, it behaved exactly as a ||= b . The second run resulted in an additional assignment. This has happened, because the first argument of the || operator is in this case the assignment a = a.

# "a || a = b"
> operation = Operation.new
> object = ValueObject.new

> object.value = operation.result('foo') unless object.value
calculating result for foo...
assigning foo to the value
=> "foo"
> value = operation.result('bar') unless object.value
=> nil

The second approximation - a = b unless a behaves like a ||= b when it is called the first time, but returns nil, when it is called for the second time. This is happening, because object.value has some value, so evaluates to true, so unless statement won't execute any code.

# "a || a = b"
> operation = Operation.new
> object = ValueObject.new

> object.value || object.value = operation.result('foo')
calculating result for foo...
assigning foo to the value
=> "foo"
> object.value || object.value = operation.result('foo')
=> "foo"

The second approximation a = a || b behaves just like the a ||= b , so it looks like we found the most accurate one.

Digging deeper

In all previous examples the variable a had some value (nil, or false), and object.value was an instance variable, so it was initialized whenever it was referenced.

> a ||= 'foo'
=> "foo"

> a ||= 'bar'
=> "foo"

> b || b = 'foo'
Traceback (most recent call last):
#(...)
NameError (undefined local variable or method `b' for main:Object)

It turns out, that our approximation does not work when we work with local, uninitialized variables.

Wrap-up

Translating all of the above to plain English: a||=b means assign b to a only if a is unassigned or evaluates to false.

Mateusz Woźniczka
Ruby Developer

Check my Twitter

Check my Linkedin

Did you like it? 

Sign up To VIsuality newsletter

READ ALSO

WebUSB - Bridge between USB devices and web browsers

14
.
11
.
2023
Burak Aybar
Ruby on Rails
Frontend
Backend
Tutorial

Visuality comes to town - this time it's Poznań

14
.
11
.
2023
Michał Piórkowski
Visuality
HR

CSS Modules in Rails

14
.
11
.
2023
Adam Król
Ruby on Rails
Tutorial
Backend
Frontend

How to choose a software house.

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Business
Visuality

JSON API versus the NIH syndrome

14
.
11
.
2023
Nadia Miętkiewicz
Backend
Frontend
Tutorial

From Idea to Concept

02
.
10
.
2024
Michał Krochecki
Ruby on Rails
Business
Startups

Styling React Components

14
.
11
.
2023
Umit Naimian
Ruby on Rails
Frontend
Tutorial

How good design can help your business grow

14
.
11
.
2023
Lukasz Jackiewicz
Design
Business
Marketing

TODO not. Do, or do not.

29
.
11
.
2023
Stanisław Zawadzki
Ruby on Rails
Software

CS Lessons #003: Density map in three ways

14
.
11
.
2023
Michał Młoźniak
Ruby
Backend
Tutorial
Software

Clean code for the win

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Backend
Frontend
Business

Crowd-operated Christmas Lights

14
.
11
.
2023
Nadia Miętkiewicz
Ruby on Rails
Backend

How to startup and be mature about it

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails
Startups
Business

A journey of a thousand miles begins with workshops

14
.
11
.
2023
Michał Piórkowski
Software
HR

CS Lessons #002: Data structures

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Summary of Phoenix workshop at Visuality

14
.
11
.
2023
Karol Słuszniak
Ruby on Rails
Visuality
Backend

CS Lessons #000: Introduction and motivation

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

CS Lessons #001: Working with binary files

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Working with 40-minute intervals

14
.
11
.
2023
Sakir Temel
Software
HR

THE MATURE TECH STARTUP DILEMMA: WHAT'S NEXT

14
.
11
.
2023
Susanna Romantsova
Startups

Win MVP workshop!

14
.
11
.
2023
Susanna Romantsova
Startups

FINTECH WEEK IN OSLO: WHATs & WHYs

14
.
11
.
2023
Susanna Romantsova
Conferences

MY FIRST MONTH AT VISUALITY

14
.
11
.
2023
Susanna Romantsova
Visuality
HR

NASA 1st global hackaton in Poland? Visuality Created it!

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails

Berlin StartupCamp 2016 summary

14
.
11
.
2023
Michał Piórkowski
Conferences
Startups