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é ;
yieldest 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;
yieldis 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 # 1yield # 2
deux_fois { print "x " }— L'appelant confie un morceau de code, le bloc, à la méthodedeux_fois. Rien ne s'exécute encore : la méthode décide quand.The caller hands a piece of code, the block, to the methoddeux_fois. Nothing runs yet: the method decides when.yield # 1— Premieryield: la méthode rappelle le bloc, qui affichex, puis le contrôle revient à la méthode.Firstyield: the method calls the block back, which printsx, then control returns to the method.yield # 2— Secondyield: même bloc, rappelé une deuxième fois. C'est la méthode qui choisit combien de fois, pas l'appelant.Secondyield: same block, called back a second time. The method chooses how many times, not the caller.
La preuve, avec Ruby 3.4
def deux_fois
yield
yield
end
deux_fois { print "x " } # => x xLa 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_gardeno 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 } # => 10Le bloc, capturé en objet
def capture(&b) = b
pr = capture { |x| x + 1 }
p pr.class # => Proc
p pr.call(1) # => 2Un 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 # => 1return 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 xThe method calls the block twice: the caller wrote no loop.
The error, as Ruby writes it
def sans_garde = yield
sans_gardeno 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 } # => 10The block, captured as an object
def capture(&b) = b
pr = capture { |x| x + 1 }
p pr.class # => Proc
p pr.call(1) # => 2A 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 # => 1return 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.