Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

Assignment Operators

Assignment 12 minCompound assignment like x += y is shorthand for x = x + y, x ||= y assigns only when x is nil or false, and parallel assignment sets or swaps several variables at once.

ruby / Assignment Operators

Explore each scene at your own pace.

01 · The rule

The rule

Assignment Operators

Compound assignment like x += y is shorthand for x = x + y, x ||= y assigns only when x is nil or false, and parallel assignment sets or swaps several variables at once.

Distinguish assignment from mutation and inspect conditional assignment.

All day, Bean Cart's script updates numbers: one more cup sold, a little more in the till, a default name if the customer gave none. Writing cups_sold = cups_sold + 1 every time is noisy. Ruby's assignment shortcuts say the same thing in fewer characters, and one of them, ||=, is a Ruby favourite.

The rule

x op= y means x = x op y; x ||= y fills only a blank.

Plain = points a name at an object:

cups_sold = 0

Every arithmetic operator has a shortcut form that updates a variable using its current value:

cups_sold += 1     # cups_sold = cups_sold + 1
till -= 2.50       # till = till - 2.50 (change given)
price *= 1.05      # price = price * 1.05
batch /= 2         # batch = batch / 2

They work with anything that has the operator, so receipt += "\nTea 2.50" extends a string.

||= assigns only when the variable is currently nil or false (or does not exist yet):

name = nil
name ||= "Guest"   # name is now "Guest"
name ||= "Sam"     # name stays "Guest"; it was already set

It is short for name || name = "Guest", so it never overwrites a real value. It is perfect for defaults and for "work this out once, then reuse it". The trap: because false also counts as blank, open ||= true will overwrite a deliberate false.

The companion &&= assigns only when the variable is already truthy: name &&= name.strip tidies a name only if there is one.

Parallel assignment sets several names at once, and swaps become a single line:

small, large = 3.50, 4.50
small, large = large, small   # swapped: small 4.5, large 3.5
first, *rest = ["latte", "tea", "mocha"]
# first = "latte", rest = ["tea", "mocha"]

Remember that Ruby has no ++; += 1 is the idiom.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.