a = b ne copie rien : le modèle mental des références en Ruby a = b copies nothing: the mental model of references in Ruby

En Ruby, a = b copie la flèche, pas l'objet : deux noms, un seul objet. Muter se voit des deux côtés, réaffecter non. Animation et sorties réelles de Ruby 3.4.In Ruby, a = b copies the arrow, not the object: two names, one object. Mutating shows on both sides, reassigning doesn't. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
RéférencesReferences
PubliéPublished

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 = b copie 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 = b copies the arrow, not the object. Before mutating, ask who else holds this same object.

a = "salut"
b = a
b << " toi"
Des noms, des objetsNames and objectsa = "salut"a = "salut"ab"salut"les objets vivent ici ; les noms ne font que les désignerobjects live here; names only point at themvérifié avec Ruby 3.4checked with Ruby 3.4
  1. a = "salut" — Le nom a pointe vers un objet String.The name a points to a String object.
  2. b = a — b = a copie la flèche, pas l'objet : deux noms, un seul objet. a.equal?(b) vaut true.b = a copies the arrow, not the object: two names, one object. a.equal?(b) is true.
  3. b << " toi" — << modifie l'objet lui-même : a vaut aussi "salut toi". Personne n'a touché à a.<< changes the object itself: a is also "salut toi". Nobody touched a.
Références en Ruby : a = b copie la flèche, pas l'objet. Muter se voit par les deux noms ; réaffecter déplace une seule flèche.References in Ruby: a = b copies the arrow, not the object. Mutating shows through both names; reassigning moves a single arrow.

La preuve, avec Ruby 3.4

a = "salut"
b = a
b << " toi"

p a             # => "salut toi"
p a.equal?(b)   # => true

a 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)   # => false

Ce 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)   # => true

a 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)   # => false

What 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.

Questions fréquentesFrequently asked questions

a = b copie-t-il l'objet en Ruby ?Does a = b copy the object in Ruby?

Non. Il fait pointer les deux noms vers le même objet. a.equal?(b) vaut true. Pour une copie distincte, il faut dup ou clone.No. It makes both names point to the same object. a.equal?(b) is true. For a separate copy you need dup or clone.

Pourquoi modifier b change-t-il a ?Why does changing b change a?

Parce que << (comme gsub!, push…) modifie l'objet lui-même, que les deux noms désignent. Rien n'a changé du côté de a : c'est l'objet qui a changé.Because << (like gsub!, push…) modifies the object itself, which both names refer to. Nothing changed on a's side: the object did.

Quelle différence entre b << x et b += x ?What's the difference between b << x and b += x?

<< mute l'objet en place, visible par tous ses noms. += construit un nouvel objet et le rattache à b ; les autres noms gardent l'ancien.<< mutates the object in place, visible through all its names. += builds a new object and rebinds b to it; other names keep the old one.

Une méthode peut-elle modifier l'argument de l'appelant ?Can a method modify the caller's argument?

Oui, si elle le mute : def ajoute(s) = s << "X" modifie la chaîne passée. Si elle réaffecte son paramètre, l'appelant ne voit rien.Yes, if it mutates it: def ajoute(s) = s << "X" changes the string passed in. If it reassigns its parameter, the caller sees nothing.

Les nombres se comportent-ils pareil ?Do numbers behave the same way?

Les entiers sont immuables : y += 1 crée toujours une nouvelle valeur, donc x reste à 5. Le piège concerne les objets mutables : chaînes, tableaux, hashes.Integers are immutable: y += 1 always creates a new value, so x stays at 5. The trap concerns mutable objects: strings, arrays, hashes.

RubyRéférencesMutationequal?Modèle mental

← Tous les articlesAll articles