« no block given (yield) » : le modèle mental des blocs en Ruby "no block given (yield)": the mental model of blocks in Ruby

each n'est pas la boucle de Ruby : c'est une méthode qui rappelle un bloc avec yield. Le modèle en une image : tu fournis le quoi, la méthode garde le comment. Animation et sorties réelles de Ruby 3.4.each isn't Ruby's loop: it's a method that calls a block back with yield. The model in one picture: you supply the what, the method keeps the how. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
BlocsBlocks
PubliéPublished

En bref. En Ruby, each { |n| … } n’est pas une boucle intégrée : each est une méthode, le bloc est un morceau de code qu’on lui confie, et c’est elle qui le rappelle avec yield, quand et autant de fois qu’elle veut.

Le modèle en une phrase

Tu fournis le quoi, la méthode garde le comment. Le bloc est du code confié ; yield est la méthode qui le rappelle.

Le contrôle est délégué : l’appelant écrit ce qu’il faut faire pour un élément, la méthode décide de l’ordre, du nombre de fois et de l’arrêt.

In short. In Ruby, each { |n| … } isn’t a built-in loop: each is a method, the block is a piece of code you hand it, and it calls the block back with yield, when and as often as it likes.

The model in one sentence

You supply the what, the method keeps the how. The block is handed-over code; yield is the method calling it back.

Control is delegated: the caller writes what to do for one element, the method decides the order, the number of times and when to stop.

deux_fois { print "x " }
yield # 1
yield # 2
Qui garde le contrôleWho keeps controlla méthode rappelle le blocthe method calls the block backl'appelantthe caller{ print "x " }le blocthe blockla méthode the method deux_foisyieldyieldsortie : output: —vérifié avec Ruby 3.4checked with Ruby 3.4
  1. deux_fois { print "x " } — L'appelant confie un morceau de code, le bloc, à la méthode deux_fois. Rien ne s'exécute encore : la méthode décide quand.The caller hands a piece of code, the block, to the method deux_fois. Nothing runs yet: the method decides when.
  2. yield # 1 — Premier yield : la méthode rappelle le bloc, qui affiche x, puis le contrôle revient à la méthode.First yield: the method calls the block back, which prints x, then control returns to the method.
  3. yield # 2 — Second yield : même bloc, rappelé une deuxième fois. C'est la méthode qui choisit combien de fois, pas l'appelant.Second yield: same block, called back a second time. The method chooses how many times, not the caller.
Bloc et yield en Ruby : l'appelant confie un bloc, la méthode le rappelle avec yield, autant de fois qu'elle veut.Block and yield in Ruby: the caller hands over a block, the method calls it back with yield, as many times as it likes.

La preuve, avec Ruby 3.4

def deux_fois
  yield
  yield
end

deux_fois { print "x " }   # => x x

La méthode appelle le bloc deux fois : l’appelant n’a écrit aucune boucle.

L’erreur, telle que Ruby l’écrit

def sans_garde = yield

sans_garde
no block given (yield) (LocalJumpError)

Sans bloc, yield n’a rien à rappeler. La parade est de tester avant :

def avec_bloc = block_given? ? yield(5) : "pas de bloc"

p avec_bloc                  # => "pas de bloc"
p avec_bloc { |n| n * 2 }    # => 10

Le bloc, capturé en objet

def capture(&b) = b

pr = capture { |x| x + 1 }
p pr.class     # => Proc
p pr.call(1)   # => 2

Un bloc n’est pas une valeur. Avec &b, il devient un Proc, qu’on peut stocker, passer et appeler plus tard.

Un piège : return dans un bloc

def meth_ret
  [1, 2].each { |x| return x }
  :fin
end

p meth_ret   # => 1

return quitte la méthode qui contient le bloc, pas seulement le bloc : :fin n’est jamais atteint.

Ce que l’image cache

Le dessin ne montre qu’un bloc sans arguments. En vrai, yield passe des valeurs (yield(5)), et le bloc en renvoie une, ce qui fait fonctionner map et select. Un bloc capture aussi les variables autour de lui : c’est la fermeture, objet d’un autre numéro.

Pour aller plus loin

Le numéro ci-dessous détaille yield, la délégation du contrôle et les arguments de bloc, avec des exercices pour réécrire des boucles en méthodes à bloc.

The proof, with Ruby 3.4

def deux_fois
  yield
  yield
end

deux_fois { print "x " }   # => x x

The method calls the block twice: the caller wrote no loop.

The error, as Ruby writes it

def sans_garde = yield

sans_garde
no block given (yield) (LocalJumpError)

With no block, yield has nothing to call back. The remedy is to check first:

def avec_bloc = block_given? ? yield(5) : "pas de bloc"

p avec_bloc                  # => "pas de bloc"
p avec_bloc { |n| n * 2 }    # => 10

The block, captured as an object

def capture(&b) = b

pr = capture { |x| x + 1 }
p pr.class     # => Proc
p pr.call(1)   # => 2

A block isn’t a value. With &b, it becomes a Proc, which you can store, pass and call later.

A trap: return inside a block

def meth_ret
  [1, 2].each { |x| return x }
  :fin
end

p meth_ret   # => 1

return exits the method that contains the block, not just the block: :fin is never reached.

What the picture hides

The drawing shows a block with no arguments. In reality yield passes values (yield(5)), and the block returns one, which is what makes map and select work. A block also captures the variables around it: that’s the closure, the subject of another issue.

Go deeper

The issue below details yield, delegated control and block arguments, with exercises for rewriting loops as block-taking methods.

Questions fréquentesFrequently asked questions

Que fait yield en Ruby ?What does yield do in Ruby?

yield rappelle le bloc passé à la méthode courante, avec les arguments donnés, et renvoie la valeur du bloc. La méthode peut l'appeler zéro, une ou plusieurs fois : c'est elle qui garde le contrôle.yield calls back the block passed to the current method, with the given arguments, and returns the block's value. The method can call it zero, one or many times: it keeps control.

Que signifie « no block given (yield) » ?What does "no block given (yield)" mean?

La méthode a exécuté yield alors que l'appelant ne lui a pas passé de bloc. Ruby lève LocalJumpError. On évite l'erreur en testant block_given? avant de faire yield.The method ran yield but the caller passed no block. Ruby raises LocalJumpError. Avoid it by testing block_given? before yielding.

Un bloc est-il un objet en Ruby ?Is a block an object in Ruby?

Pas tel quel : un bloc n'est pas une valeur qu'on manipule. Pour le stocker ou le passer, on le capture avec &bloc, ce qui donne un objet Proc.Not as is: a block isn't a value you can handle. To store or pass it, capture it with &block, which gives a Proc object.

Quelle différence entre each et une boucle for ?What's the difference between each and a for loop?

each est une méthode qui reçoit un bloc et le rappelle pour chaque élément ; la collection décide comment parcourir. for est une construction du langage. Idiomatiquement, on utilise each, map, select.each is a method that receives a block and calls it back for each element; the collection decides how to iterate. for is a language construct. Idiomatically, you use each, map, select.

Que fait return dans un bloc ?What does return do inside a block?

Il quitte la méthode qui contient le bloc, pas seulement le bloc. Dans [1, 2].each { |x| return x }, la méthode englobante renvoie 1 et le reste ne s'exécute pas.It exits the method that contains the block, not just the block. In [1, 2].each { |x| return x }, the enclosing method returns 1 and nothing else runs.

RubyBlocsyieldLocalJumpErrorModèle mental

← Tous les articlesAll articles