Who points at what?
In Ruby a variable doesn't contain the object itself – it only points at it, like a name tag on a box. Assign it to a second variable and the same box gets a second tag. That surprises almost everyone at some point:
monday = ["ProjectX"]
tuesday = monday
tuesday << "Intern"
mondaymonday changed although we only worked on tuesday – it's one and the same array. equal? checks whether two names point at the same object; == only checks whether the contents are equal. And object_id is, so to speak, the number of the box:
p tuesday.equal?(monday)
p tuesday == ["ProjectX", "Intern"]
p tuesday.equal?(["ProjectX", "Intern"])
monday.object_id == tuesday.object_idIf you want a real copy, say so: dup builds a new object with the same content. Afterwards the two are independent of each other:
wednesday = monday.dup
wednesday << "Support"
[monday, wednesday]But careful: dup only copies the outermost layer – a shallow copy. If the array holds hashes, original and copy share the very same hashes:
entries = [{ project: "A", hours: 2.0 }]
copy = entries.dup
copy.first[:hours] = 99
entries.first[:hours]For a deep copy you copy every level yourself, for instance with entries.map(&:dup).
The same trap hides in a classic: Hash.new with an array as the default value. Every missing key gets the same array:
by_project = Hash.new([])
by_project["A"] << 2.0
by_project["B"] << 1.5
[by_project["C"], by_project.keys]Two surprises at once: the “empty” default value is no longer empty at all, and the hash has no keys whatsoever – << only changed the shared default array and never stored anything in the hash. The fix is a block: it runs anew for every missing key, creates an array of its own and stores it:
by_project = Hash.new { |hash, key| hash[key] = [] }
by_project["A"] << 2.0
by_project["B"] << 1.5
by_projectThe safest protection against unwanted changes: freeze objects. freeze makes an object unchangeable. Anyone who tries anyway gets a FrozenError – at once and right where it happens, instead of as puzzlingly wrong data at some later point:
projects = ["ProjectX", "Intern"].freeze
p projects.frozen?
projects << "Secret"Frozen objects can be shared without danger. That's why numbers and symbols are always frozen, and Data (lesson 113) freezes its objects by itself. Many Ruby files start with the magic comment # frozen_string_literal: true: then every string written in quotes in that file's code is frozen.
Three rules of thumb to take along: methods with ! (sort!, upcase!) change the object, methods without return a new one. Hand out objects that others must not change frozen or as a copy. And when something changes “all by itself”: ask yourself who else points at the same box.
Logbook below has a leak: entries hands out the internal list, and whoever changes it changes the logbook too. Repair entries so that it returns a frozen copy. Then nobody can smuggle entries in from outside anymore – but add must keep working.class Logbook
def initialize
@entries = []
end
def add(project, hours)
@entries << { project: project, hours: hours }
self
end
def entries
@entries # the leak: the internal list itself
end
end
log = Logbook.new.add("ProjectX", 3.5)
log.entries.frozen?