Reason #22 • January 22nd, 2026

Conditional assignment

In Ruby, we can use the conditional assignment operator ||= to assign a value to a variable only if that variable is currently falsy (i.e. nil or false). This is particularly useful for assigning default values.

Ruby
ENV["ENVIRONMENT"] ||= "development"

def paginated_get_request(path, parameters = {}, headers = {})
  parameters["page"] ||= 1
  parameters["per_page"] ||= 20
  parameters["sort_by"] ||= "name"
  parameters["sort_order"] ||= "asc"

  headers["accept"] ||= "application/json"
  headers["accept-encoding"] ||= "gzip"

  # ...
end

def nested_data_with_defaults(data = {})
  data["user"] ||= {}
  data["user"]["name"] ||= "Guest"
  data["user"]["role"] ||= "viewer"
  data["settings"] ||= {}
  data["settings"]["theme"] ||= "light"
  data["settings"]["language"] ||= "en"

  # ...
end
    

History

The ||= operator has been part of Ruby since its inception. However, the first language to introduce it was Perl. Not many other languages support this idiom, but JavaScript is among them, though it received its own logical assignment operators ??= and ||= much later as part of the ECMAScript 2021 specification.

The operator has arguably become less important since the introduction of keyword arguments in Ruby 2.0, which allow for default values of "option-like arguments" to be specified directly in method signatures.

That said, there is a ubiquitous pattern used all over Ruby code that relies on ||=, and we have yet to talk about it. Stay tuned!