Or Equals Operator
The ||=
operator is a conditional assignment operator. It assigns the right-hand value to the left-hand variable if the left-hand value is falsy. It is often referred to as the memoization operator.
This is one of many operators where =
gets tacked on to the end as a shorthand. These two code snippets are equivalent.
Using boolean or followed by an assignment:
who = nil # not set yet
who = who || 'friend'
puts "Hello, #{who}!" #=> Hello, friend!
Using the ||=
operator:
who = nil # not set yet
who ||= 'friend'
puts "Hello, #{who}!" #=> Hello, friend!
Here is a more practical example.
class SomeController < ApplicationController
def index
@recent_books = books_by_status(:recent)
@abandoned_books = books_by_status(:abandoned)
end
private
def external_books
@external_books ||= begin
user_identifier = current_user.book_api_identifier
ExternalBookApi.fetch_books(user_identifier) #=> array of book hashes
end
end
def books_by_status(status)
external_books.select { |book| book[:status] == status }
end
end
We don't want to make an expensive, redundant, and possibly billable external API call multiple times if we don't have to. The ||=
operator memoizes the result of that block in @external_books
. Each subsequent call the external_books
method will return the memoized value.