Assignment Operators
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= ymeansx = x op y;x ||= yfills only a blank.
Plain = points a name at an object:
cups_sold = 0Every 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 / 2They 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 setIt 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.
The shortcut
To read any shortcut, unfold it: move the operator to the right-hand side and repeat the variable's name. For ||=, unfold it to "is it blank? then set it".
Start
cups_sold = 11,till = 40.0,customer = nil.
Drills
Answer fast — trust the rule.
After till = 20 and till -= 4, what is till?
After name = "Priya" and name ||= "Guest", what is name?
After open = false and open ||= true, what is open?
After a, b = 1, 2 and a, b = b, a, what are a and b?
Remember
x op= ymeansx = x op y;x ||= yfills only a blank (nil or false).- Unfold any shortcut to read it; use parallel assignment to swap.
- Trap:
||=overwrites a deliberatefalse, and Ruby has no++.
