Le { … } n'est pas la boucle. C'est du code que tu confies.The { … } isn't the loop. It's code you hand over.
On lit each { |n| … } comme « la façon de boucler en Ruby ». C'est passer à côté de tout. each est une méthode ordinaire ; le bloc entre accolades est un morceau de code qu'on lui confie ; et c'est each qui décide de le rappeler — une fois par élément, via yield. La boucle n'est pas une construction du langage : c'est un objet à qui on a délégué le contrôle.We read each { |n| … } as 'how you loop in Ruby'. That misses everything. each is an ordinary method; the block in braces is a piece of code you hand it; and it's each that decides to call it back — once per element, via yield. The loop isn't a language construct: it's an object you've delegated control to.
[1, 2, 3].each { |n| puts n } # le { |n| puts n } n'est pas "la boucle" : # c'est un BLOC — un morceau de code — qu'on CONFIE à each. # each le rappelle une fois par élément, avec yield. def twice yield # exécute le bloc qu'on m'a passé yield # … et je décide de le rappeler une seconde fois end twice { puts "go" } # affiche "go" deux fois
Tu fournis le quoi (le bloc) ; la méthode garde le quand et le combien de fois. C'est l'inversion de contrôle.You supply the what (the block); the method keeps the when and the how many times. That's inversion of control.
« Ce comportement, je le passe en bloc — et c'est l'objet receveur qui décide quand l'exécuter. » Au lieu d'écrire une boucle qui fait les choses, on confie le corps à une méthode qui sait comment itérer, ouvrir, réessayer, nettoyer. Le bloc dit le quoi ; la méthode orchestre le comment."This behavior, I pass it as a block — and the receiving object decides when to run it." Instead of writing a loop that does things, you hand the body to a method that knows how to iterate, open, retry, clean up. The block says the what; the method orchestrates the how.
Le Vol 1 a posé : tout est un message à un objet. Le bloc est la suite naturelle — on envoie un message à un objet en lui joignant un morceau de code, et on le laisse décider quoi en faire. each, map, open, transaction : toujours le même geste. Comprends yield, et la moitié de la bibliothèque standard cesse d'être magique.Vol 1 established: everything is a message to an object. The block is the natural sequel — you send a message to an object with a piece of code attached, and let it decide what to do with it. each, map, open, transaction: always the same gesture. Understand yield, and half the standard library stops being magic.