« undefined local variable » : le modèle mental des closures en Ruby "undefined local variable": the mental model of closures in Ruby

Une closure n'emporte pas une copie de ses variables, mais un lien vers elles, vivant. Une méthode, elle, n'en capture aucune. Animation et sorties réelles de Ruby 3.4.A closure doesn't carry a copy of its variables but a live link to them. A method captures none. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
BlocsBlocks
PubliéPublished

En bref. Un bloc ou une lambda emporte son contexte, mais comme un lien vers les variables, pas comme une photo de leurs valeurs. Une méthode def, elle, n’emporte rien.

Le modèle en une phrase

Une closure garde un lien vers la variable vivante, pas une copie.

In short. A block or lambda carries its context, but as a link to the variables, not a snapshot of their values. A def method carries nothing.

The model in one sentence

A closure keeps a link to the live variable, not a copy.

x = 10; add = ->(y) { x + y }
x = 20
add.call(1) # => 21
Un lien, pas une copieA link, not a copyla variable reste vivantethe variable stays livela variablethe variablex = 10la lambdathe lambda->(y) { x + y }lien vivantlive linkrésultat : result: —vérifié avec Ruby 3.4checked with Ruby 3.4
  1. x = 10; add = ->(y) { x + y } — La lambda naît à côté de x et garde un lien vers elle, pas une photo de sa valeur.The lambda is born next to x and keeps a link to it, not a snapshot of its value.
  2. x = 20 — On change x après coup. Le lien est toujours là : la lambda verra la nouvelle valeur.We change x afterwards. The link is still there: the lambda will see the new value.
  3. add.call(1) # => 21 — Résultat 21, pas 11 : la variable est vivante, lue au moment de l'appel.Result 21, not 11: the variable is live, read at call time.
Fermeture en Ruby : la lambda garde un lien vers la variable vivante, pas une copie de sa valeur.Closure in Ruby: the lambda keeps a link to the live variable, not a copy of its value.

La preuve, avec Ruby 3.4

x = 10
add = ->(y) { x + y }
x = 20
p add.call(1)   # => 21, pas 11

La lambda lit x au moment de l’appel, pas à sa création.

Le compteur

def compteur
  n = 0
  -> { n += 1 }
end

c = compteur
p c.call, c.call, c.call   # => 1, 2, 3
p compteur.call            # => 1

La variable n survit à la fin de compteur parce que la lambda la tient. Chaque appel de compteur crée son propre n.

L’erreur, telle que Ruby l’écrit

x = 10
def m; x; end
m
undefined local variable or method 'x' for main (NameError)

def ouvre une portée neuve : x n’y existe pas.

Dans une boucle

procs = []
3.times { |i| procs << -> { i } }
p procs.map(&:call)   # => [0, 1, 2]

Chaque tour du bloc a sa propre variable i : chaque lambda garde la sienne.

Ce que l’image cache

Le dessin montre une seule variable. Une closure peut en tenir plusieurs, et plusieurs closures peuvent tenir la même : elles se voient alors mutuellement, ce qui est la force des compteurs et le piège des variables partagées.

Pour aller plus loin

Le numéro ci-dessous développe les caches, les générateurs et les pièges de variables partagées, avec des exercices.

The proof, with Ruby 3.4

x = 10
add = ->(y) { x + y }
x = 20
p add.call(1)   # => 21, not 11

The lambda reads x at call time, not at creation.

The counter

def compteur
  n = 0
  -> { n += 1 }
end

c = compteur
p c.call, c.call, c.call   # => 1, 2, 3
p compteur.call            # => 1

The variable n outlives compteur because the lambda holds it. Each call to compteur creates its own n.

The error, as Ruby writes it

x = 10
def m; x; end
m
undefined local variable or method 'x' for main (NameError)

def opens a fresh scope: x doesn’t exist there.

In a loop

procs = []
3.times { |i| procs << -> { i } }
p procs.map(&:call)   # => [0, 1, 2]

Each iteration of the block has its own i: each lambda keeps its own.

What the picture hides

The drawing shows one variable. A closure can hold several, and several closures can hold the same one: they then see each other’s changes, which is the strength of counters and the trap of shared variables.

Go deeper

The issue below covers caches, generators and shared-variable traps, with exercises.

Questions fréquentesFrequently asked questions

Qu'est-ce qu'une closure en Ruby ?What is a closure in Ruby?

Un bloc, un proc ou une lambda qui garde l'accès aux variables locales présentes là où il a été créé, même après que ce contexte a fini de s'exécuter.A block, proc or lambda that keeps access to the local variables present where it was created, even after that context has finished running.

Une closure capture-t-elle la valeur ou la variable ?Does a closure capture the value or the variable?

La variable, pas sa valeur. Si x passe de 10 à 20 après la création de la lambda, elle lit 20 à l'appel.The variable, not its value. If x goes from 10 to 20 after the lambda is created, it reads 20 when called.

Pourquoi une méthode def ne voit-elle pas les variables locales autour ?Why doesn't a def method see the surrounding local variables?

def ouvre une portée neuve. Seuls les blocs, procs et lambdas capturent le contexte. Dans la méthode, x est cherchée comme méthode puis NameError.def opens a fresh scope. Only blocks, procs and lambdas capture context. Inside the method, x is looked up as a method, then NameError.

Comment faire un compteur avec une closure ?How do I build a counter with a closure?

Une méthode crée une variable locale n = 0 et renvoie -> { n += 1 }. Chaque appel de la méthode crée sa propre variable n : deux compteurs sont indépendants.A method creates a local n = 0 and returns -> { n += 1 }. Each call of the method creates its own n: two counters are independent.

Les closures dans une boucle partagent-elles la même variable ?Do closures created in a loop share the same variable?

Avec un bloc comme 3.times { |i| … }, chaque tour a sa propre variable i, donc chaque closure garde sa valeur. Avec une variable déclarée hors du bloc, toutes partagent la même.With a block like 3.times { |i| … }, each iteration has its own i, so each closure keeps its value. With a variable declared outside the block, they all share it.

RubyClosuresPortéeNameErrorModèle mental

← Tous les articlesAll articles