« wrong number of arguments » : le modèle mental de Proc et lambda en Ruby "wrong number of arguments": the mental model of Proc and lambda in Ruby

Un proc et une lambda sont le même objet Proc, avec deux politiques : souple ou stricte sur les arguments, return qui quitte la méthode ou qui revient à l'appelant. Animation et sorties réelles de Ruby 3.4.A proc and a lambda are the same Proc object with two policies: lenient or strict on arguments, return that exits the method or goes back to the caller. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
BlocsBlocks
PubliéPublished

En bref. Un proc et une lambda sont le même objet, Proc. Ils diffèrent par deux règles : la lambda est stricte sur les arguments, et son return ne sort que d’elle-même.

Le modèle en une phrase

Le proc est un fragment de code ; la lambda est une petite fonction. Même objet, deux politiques.

In short. A proc and a lambda are the same object, Proc. They differ by two rules: a lambda is strict about arguments, and its return only leaves itself.

The model in one sentence

A proc is a code fragment; a lambda is a small function. Same object, two policies.

pr = proc { |a, b| [a, b] }
pr.call(1) # => [1, nil]
proc { return 1 }.call
Même Proc, deux politiquesSame Proc, two policieslambda? : falselambda?: falsel'objet : the object: proc { |a, b| }arguments : arguments: call(1)[1, nil]return dans le corps in the bodyrevient à l'appelantback to the callervérifié avec Ruby 3.4checked with Ruby 3.4
  1. pr = proc { |a, b| [a, b] } — On crée un Proc à deux paramètres. pr.lambda? vaut false.We create a Proc with two parameters. pr.lambda? is false.
  2. pr.call(1) # => [1, nil] — Un seul argument donné : le proc est souple, b vaut nil. Aucune erreur.Only one argument given: the proc is lenient, b is nil. No error.
  3. proc { return 1 }.call — return dans un proc quitte la méthode qui l'entoure : la ligne suivante n'est jamais atteinte.return inside a proc exits the enclosing method: the next line is never reached.
Proc et lambda en Ruby : un même objet Proc ; le proc est souple sur les arguments et son return quitte la méthode, la lambda est stricte et son return revient à l'appelant.Proc and lambda in Ruby: the same Proc object; a proc is lenient with arguments and its return exits the method, a lambda is strict and its return goes back to the caller.

La preuve, avec Ruby 3.4

pr = proc   { |a, b| [a, b] }
la = lambda { |a, b| [a, b] }

p pr.call(1)          # => [1, nil]
p pr.call(1, 2, 3)    # => [1, 2]
p pr.call([4, 5])     # => [4, 5]
p pr.lambda?, la.lambda?   # => false, true

Le proc s’arrange avec ce qu’on lui donne : il complète avec nil, ignore l’excédent et déballe un tableau.

L’erreur, telle que Ruby l’écrit

la.call(1)
wrong number of arguments (given 1, expected 2) (ArgumentError)

La lambda se comporte comme une méthode : le bon nombre d’arguments, sinon ArgumentError.

Le piège : return

def t_proc
  pr = proc { return 1 }
  pr.call
  2
end

def t_lam
  l = -> { return 1 }
  l.call
  2
end

p t_proc   # => 1
p t_lam    # => 2

Le return du proc quitte t_proc : le 2 n’est jamais atteint. Celui de la lambda revient juste à l.call, et la méthode continue.

Ce que l’image cache

Les blocs passés avec & se comportent comme des procs, pas comme des lambdas. Et lambda? ne dit rien de la portée : proc comme lambda capturent les variables autour d’eux, c’est la fermeture, objet d’un autre numéro.

Pour aller plus loin

Le numéro ci-dessous compare les deux dans le détail (arité, return, curry, conversion en bloc) avec des exercices.

The proof, with Ruby 3.4

pr = proc   { |a, b| [a, b] }
la = lambda { |a, b| [a, b] }

p pr.call(1)          # => [1, nil]
p pr.call(1, 2, 3)    # => [1, 2]
p pr.call([4, 5])     # => [4, 5]
p pr.lambda?, la.lambda?   # => false, true

The proc makes do with what it gets: it pads with nil, ignores the excess and unpacks an array.

The error, as Ruby writes it

la.call(1)
wrong number of arguments (given 1, expected 2) (ArgumentError)

The lambda behaves like a method: the right number of arguments, or ArgumentError.

The trap: return

def t_proc
  pr = proc { return 1 }
  pr.call
  2
end

def t_lam
  l = -> { return 1 }
  l.call
  2
end

p t_proc   # => 1
p t_lam    # => 2

The proc’s return exits t_proc: the 2 is never reached. The lambda’s only goes back to l.call, and the method carries on.

What the picture hides

Blocks passed with & behave like procs, not lambdas. And lambda? says nothing about scope: both procs and lambdas capture the variables around them, that’s the closure, the subject of another issue.

Go deeper

The issue below compares the two in detail (arity, return, curry, converting to a block) with exercises.

Questions fréquentesFrequently asked questions

Quelle est la différence entre un proc et une lambda en Ruby ?What is the difference between a proc and a lambda in Ruby?

Les deux sont des objets Proc. La lambda vérifie le nombre d'arguments (ArgumentError sinon) et son return revient à son appelant ; le proc est souple sur les arguments et son return quitte la méthode englobante.Both are Proc objects. A lambda checks the number of arguments (ArgumentError otherwise) and its return goes back to its caller; a proc is lenient with arguments and its return exits the enclosing method.

Comment savoir si un Proc est une lambda ?How can I tell if a Proc is a lambda?

Avec la méthode lambda?. proc { }.lambda? vaut false, lambda { }.lambda? et -> { }.lambda? valent true.With the lambda? method. proc { }.lambda? is false, lambda { }.lambda? and -> { }.lambda? are true.

Que fait un proc quand on lui passe trop ou trop peu d'arguments ?What does a proc do with too few or too many arguments?

Il s'adapte : les arguments manquants valent nil, les arguments en trop sont ignorés. proc { |a, b| [a, b] }.call(1) renvoie [1, nil].It adapts: missing arguments are nil, extra ones are ignored. proc { |a, b| [a, b] }.call(1) returns [1, nil].

Que fait return dans un proc ?What does return do inside a proc?

Il quitte la méthode dans laquelle le proc a été créé, pas seulement le proc. Dans une lambda, return ne fait que rendre la main à l'appelant de la lambda.It exits the method in which the proc was created, not just the proc. In a lambda, return only hands control back to the lambda's caller.

Quand préférer une lambda ?When should I prefer a lambda?

Quand tu veux une vraie petite fonction : arguments vérifiés, return local. Un proc ou un bloc convient quand tu veux un fragment de code qui s'insère dans la méthode courante.When you want a real small function: checked arguments, local return. A proc or block fits when you want a code fragment that slots into the current method.

RubyProcLambdaArgumentErrorModèle mental

← Tous les articlesAll articles