← Back to Ruby Operators

Assignment Operator

A solo = symbol is used for assignment in Ruby. It is also combined with many other operators for a compound operator that does the operation and then assigns the resulting value.

> food = :taco
=> :taco
> food
=> :taco

We might see assignment happen from a method call or block expression.

> squares = [1,2,3].map { |n| n * n }
=> [1, 4, 9]
> full_name = begin
  first_name = "Bob"
  last_name = "Burgers"
  "#{first_name} #{last_name}"
end
=> "Bob Burgers"

Another common pattern in Ruby is a single-line if statement which can be combined with an assignment. The Ruby Docs have an example that demonstrates both this and the way that a variable declaration is hoisted to the top of the scope.

a = 0 if false # does not assign to a

p local_variables # prints [:a]

p a # prints nil

Abbreviated Assignment Operators

Then there are all the composite assignment operators like +=, -=, *=, /=, %=, **=, &=, |=, ^=, >>=, and <<=. The Ruby Docs call these Abbreviated Assignment Operators.

Let's look at two equivalent statements:

> x = 5
=> 5
> x = x + 1
=> 6
> x = 5
=> 5
> x += 1
=> 6

These operators allow us to write terser code. While the += operator is probably showing up from time to time in our codebases, I bet we're rarely seeing many of these other ones.

> x = 11
=> 11
> x %= 3
=> 2
> x **= 4
=> 16

Conditional Assignment Operators

Related to the above are the two conditional assignment operators ||= and &&=. The ||= operator is fairly common in idiomatic Ruby code, whereas I'm hard-pressed to think of a time to use the &&= operator.

> x ||= 10
=> 10
> x &&= 20
=> nil

There are some good details on the ||= operator page, so be sure to check that out.

References