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

Investment Days for productivity

14
.
11
.
2023
Rafał Maliszewski
Visuality
HR

Happy new year

14
.
11
.
2023
Michał Piórkowski
Visuality

Does Norway need Polish software development?

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails

Visuality is 8 years old

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

Use less javascript plugins

14
.
11
.
2023
Michał Młoźniak
Frontend

Front-Trends 2015

14
.
11
.
2023
Adam Król
Frontend

Automatic door opener controlled through slack

14
.
11
.
2023
Sakir Temel
Backend
Software
Tutorial

Wolves Summit

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

Berlin Startup Camp

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

Why you shouldn't work at Visuality

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

SaaS Meetup #People

14
.
11
.
2023
Michał Piórkowski
Conferences

Startup Safary Berlin 2015

14
.
11
.
2023
Michał Piórkowski
Conferences

Emmet makes HTML and CSS easier

14
.
11
.
2023
Michał Piórkowski
Frontend
Tutorial

Optional dependencies in gems

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

Text messaging with textris gem

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