En bref. En Ruby, une variable n’est pas une boîte qui contient l’objet : c’est un nom qui le désigne. b = a ajoute un second nom au même objet, il ne le copie pas.
Le modèle en une phrase
a = bcopie la flèche, pas l’objet. Avant de muter, demande-toi qui d’autre tient ce même objet.
In short. In Ruby, a variable isn’t a box holding the object: it’s a name pointing at it. b = a adds a second name to the same object, it doesn’t copy it.
The model in one sentence
a = bcopies the arrow, not the object. Before mutating, ask who else holds this same object.
a = "salut"b = ab << " toi"
a = "salut"— Le nomapointe vers un objetString.The nameapoints to aStringobject.b = a—b = acopie la flèche, pas l'objet : deux noms, un seul objet.a.equal?(b)vauttrue.b = acopies the arrow, not the object: two names, one object.a.equal?(b)istrue.b << " toi"—<<modifie l'objet lui-même :avaut aussi"salut toi". Personne n'a touché àa.<<changes the object itself:ais also"salut toi". Nobody toucheda.
La preuve, avec Ruby 3.4
a = "salut"
b = a
b << " toi"
p a # => "salut toi"
p a.equal?(b) # => truea n’a jamais été touché, et pourtant il a changé : l’objet est partagé.
Réaffecter n’est pas muter
b += " encore"
p a # => "salut toi"
p b # => "salut toi encore"
p a.equal?(b) # => false+= construit un nouvel objet et déplace la flèche de b. a garde l’ancien.
À distance, par une méthode
def ajoute(s) = s << "X"
t = "t"
ajoute(t)
p t # => "tX"L’appelant retrouve sa chaîne modifiée : la méthode a reçu l’objet, pas une copie.
Copier pour de vrai
c = a.dup
c << "!"
p a # => "salut toi"
p c # => "salut toi!"
p a.equal?(c) # => falseCe que l’image cache
Les entiers, symboles, nil et true/false sont immuables : y = x; y += 1 laisse x à 5, il n’y a rien à partager. Et dup est superficiel : il copie l’objet, pas les objets qu’il contient. C’est le sujet des numéros sur freeze et sur dup contre clone.
Pour aller plus loin
Le numéro ci-dessous détaille la référence partagée et ses pièges, avec des exercices.
The proof, with Ruby 3.4
a = "salut"
b = a
b << " toi"
p a # => "salut toi"
p a.equal?(b) # => truea was never touched, and yet it changed: the object is shared.
Reassigning isn’t mutating
b += " encore"
p a # => "salut toi"
p b # => "salut toi encore"
p a.equal?(b) # => false+= builds a new object and moves b’s arrow. a keeps the old one.
At a distance, through a method
def ajoute(s) = s << "X"
t = "t"
ajoute(t)
p t # => "tX"The caller finds its string modified: the method received the object, not a copy.
Really copying
c = a.dup
c << "!"
p a # => "salut toi"
p c # => "salut toi!"
p a.equal?(c) # => falseWhat the picture hides
Integers, symbols, nil and true/false are immutable: y = x; y += 1 leaves x at 5, there is nothing to share. And dup is shallow: it copies the object, not the objects it contains. That’s the subject of the issues on freeze and on dup versus clone.
Go deeper
The issue below details the shared reference and its traps, with exercises.