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

Michal - Highlights from Ruby Unconf 2024

Highlights from Ruby Unconf 2024

14
.
11
.
2023
Michał Łęcicki
Conferences
Visuality
Cezary Kłos - Optimizing Cloud Infrastructure by $40 000 Annually

Optimizing Cloud Infrastructure by $40 000 Annually

14
.
11
.
2023
Cezary Kłos
Backend
Ruby on Rails

Smooth Concurrent Updates with Hotwire Stimulus

14
.
11
.
2023
Michał Łęcicki
Hotwire
Ruby on Rails
Software
Tutorial

Table partitioning in Rails, part 2 - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Backend
Postgresql
Ruby on Rails

N+1 in Ruby on Rails

14
.
11
.
2023
Katarzyna Melon-Markowska
Ruby on Rails
Ruby
Backend

Turbo Streams and current user

29
.
11
.
2023
Mateusz Bilski
Hotwire
Ruby on Rails
Backend
Frontend

Showing progress of background jobs with Turbo

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Ruby
Hotwire
Frontend
Backend

Table partitioning in Rails, part 1 - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend
Ruby on Rails

Table partitioning types - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend

Indexing partitioned table - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Backend
Postgresql
SQL Views in Ruby on Rails

SQL views in Ruby on Rails

14
.
11
.
2023
Jan Grela
Backend
Ruby
Ruby on Rails
Postgresql
Design your bathroom in React

Design your bathroom in React

14
.
11
.
2023
Bartosz Bazański
Frontend
React
Lazy Attributes in Ruby - Krzysztof Wawer

Lazy attributes in Ruby

14
.
11
.
2023
Krzysztof Wawer
Ruby
Software

Exporting CSV files using COPY - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Ruby
Ruby on Rails
Michał Łęcicki - From Celluloid to Concurrent Ruby

From Celluloid to Concurrent Ruby: Practical Examples Of Multithreading Calls

14
.
11
.
2023
Michał Łęcicki
Backend
Ruby
Ruby on Rails
Software

Super Slide Me - Game Written in React

14
.
11
.
2023
Antoni Smoliński
Frontend
React
Jarek Kowalewski - ILIKE vs LIKE/LOWER - Postgres Stories

ILIKE vs LIKE/LOWER - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Ruby
Ruby on Rails
Postgresql

A look back at Friendly.rb 2023

14
.
11
.
2023
Cezary Kłos
Conferences
Ruby

Debugging Rails - Ruby Junior Chronicles

14
.
11
.
2023
Piotr Witek
Ruby on Rails
Backend
Tutorial

GraphQL in Ruby on Rails: How to Extend Connections

14
.
11
.
2023
Cezary Kłos
Ruby on Rails
GraphQL
Backend
Tutorial

Tetris on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Frontend
Hotwire

EURUKO 2023 - here's what you've missed

14
.
11
.
2023
Michał Łęcicki
Ruby
Conferences

Easy introduction to Connection Pool in ruby

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

When crazy ideas bring great time or how we organized our first Conference!

04
.
12
.
2023
Alexander Repnikov
Ruby on Rails
Conferences
Visuality