« undefined method » (NoMethodError) : le modèle mental de self et du message en Ruby "undefined method" (NoMethodError): the mental model of self and messages in Ruby

Pourquoi 1 + 2 s'écrit aussi 1.+(2) en Ruby, et ce que veut dire « undefined method for nil ». Le modèle en une image : un receveur, un message, et self quand on n'écrit personne. Animation et sorties réelles de Ruby 3.4.Why 1 + 2 can also be written 1.+(2) in Ruby, and what "undefined method for nil" means. The model in one picture: a receiver, a message, and self when nobody is written. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ObjetsObjects
PubliéPublished

En bref. En Ruby, tout appel est un message envoyé à un objet. 1 + 2 est 1.+(2), et un appel sans receveur part à self. Quand l’objet n’a pas de méthode de ce nom, Ruby lève NoMethodError, à l’exécution.

Le modèle en une phrase

Un receveur, un message. On n’appelle pas une fonction : on envoie un message à un objet, qui cherche la méthode dans sa classe. Sans receveur écrit, c’est self.

Il n’y a ni opérateur câblé ni fonction libre. Même puts est une méthode, envoyée à l’objet courant.

In short. In Ruby, every call is a message sent to an object. 1 + 2 is 1.+(2), and a call with no receiver goes to self. When the object has no method of that name, Ruby raises NoMethodError, at runtime.

The model in one sentence

A receiver, a message. You don’t call a function: you send a message to an object, which looks the method up in its class. With no written receiver, it’s self.

There is no wired-in operator and no free function. Even puts is a method, sent to the current object.

1 + 2
1.+(2)
# => 3
Qui reçoit le messageWho receives the message1 + 2 = 1.+(2)1 + 2 = 1.+(2)receveurreceiver1:+méthodes de methods of Integer+-*méthode trouvéemethod foundvaleur renvoyéereturned valueself = mainvérifié avec Ruby 3.4checked with Ruby 3.4
  1. 1 + 2 — Il n'y a pas d'opérateur câblé : 1 + 2 s'écrit aussi 1.+(2). Le receveur est l'objet 1, le message est +, l'argument est 2.There is no wired-in operator: 1 + 2 can also be written 1.+(2). The receiver is the object 1, the message is +, the argument is 2.
  2. 1.+(2) — Ruby envoie le message au receveur et cherche une méthode du même nom dans sa classe, Integer. Il en trouve une : +.Ruby sends the message to the receiver and looks for a method of that name in its class, Integer. It finds one: +.
  3. # => 3 — La méthode s'exécute et renvoie 3. Rien de spécial pour les nombres : c'est le même mécanisme que pour n'importe quel objet.The method runs and returns 3. Nothing special about numbers: it's the same mechanism as for any object.
Envoi de message en Ruby : 1 + 2 est 1.+(2), le message + envoyé à l'objet 1, qui le résout dans sa classe Integer.Message sending in Ruby: 1 + 2 is 1.+(2), the + message sent to the object 1, resolved in its Integer class.

La preuve, avec Ruby 3.4

p 1 + 2           # => 3
p 1.+(2)          # => 3
p 1.send(:+, 2)   # => 3
p self            # => main
p self.class      # => Object

Les trois premières lignes font la même chose. Au niveau du script, self est un objet nommé main, de classe Object.

L’erreur, telle que Ruby l’écrit

class Chat
  def cri = miauler
  def miauler = "miaou"
end

Chat.new.cri   # => "miaou"
Chat.new.zzz
nil.zzz
undefined method 'zzz' for an instance of Chat (NoMethodError)
undefined method 'zzz' for nil (NoMethodError)

Dans cri, l’appel miauler n’a pas de receveur : Ruby l’envoie à self, l’instance de Chat. Les deux erreurs ont la même forme : un receveur (une instance de Chat, nil) et un message (zzz) qu’il ne comprend pas.

Que faire d’un undefined method … for nil

Le receveur est nil : une valeur qu’on croyait remplie ne l’est pas. Trois réflexes, du plus utile au plus défensif :

  • Remonter à la source : où la valeur est-elle devenue nil ? C’est là qu’est le vrai bug.
  • Tester le receveur avant d’envoyer : if user, ou user&.nom qui renvoie nil au lieu de lever.
  • Demander s’il sait répondre : obj.respond_to?(:nom).

Ce que l’image cache

Le dessin montre une seule classe. En vrai, Ruby cherche aussi dans les modules inclus et les classes parentes, dans un ordre précis (la chaîne d’ancêtres), avant de renoncer. Et method_missing permet à un objet d’intercepter un message qu’il ne connaît pas : c’est ce qui fait fonctionner de nombreuses bibliothèques.

Pour aller plus loin

Le numéro ci-dessous détaille self, le receveur implicite et l’envoi de message, avec des exercices pour traquer le receveur dans du vrai code.

The proof, with Ruby 3.4

p 1 + 2           # => 3
p 1.+(2)          # => 3
p 1.send(:+, 2)   # => 3
p self            # => main
p self.class      # => Object

The first three lines do the same thing. At script level, self is an object named main, of class Object.

The error, as Ruby writes it

class Chat
  def cri = miauler
  def miauler = "miaou"
end

Chat.new.cri   # => "miaou"
Chat.new.zzz
nil.zzz
undefined method 'zzz' for an instance of Chat (NoMethodError)
undefined method 'zzz' for nil (NoMethodError)

Inside cri, the call miauler has no receiver: Ruby sends it to self, the Chat instance. Both errors have the same shape: a receiver (an instance of Chat, nil) and a message (zzz) it doesn’t understand.

What to do about undefined method … for nil

The receiver is nil: a value you thought was filled in isn’t. Three reflexes, from most useful to most defensive:

  • Trace it back: where did the value become nil? That’s the real bug.
  • Check the receiver before sending: if user, or user&.name, which returns nil instead of raising.
  • Ask whether it can answer: obj.respond_to?(:name).

What the picture hides

The drawing shows a single class. In reality Ruby also searches included modules and parent classes, in a precise order (the ancestor chain), before giving up. And method_missing lets an object intercept a message it doesn’t know: that’s what powers many libraries.

Go deeper

The issue below covers self, the implicit receiver and message sending in depth, with exercises for hunting the receiver in real code.

Questions fréquentesFrequently asked questions

Que signifie « undefined method » en Ruby ?What does "undefined method" mean in Ruby?

Ruby a envoyé un message à un objet, a cherché une méthode du même nom dans sa classe et ses ancêtres, et n'en a trouvé aucune. Il lève NoMethodError, à l'exécution. Le receveur existe : c'est le message qu'il ne comprend pas.Ruby sent a message to an object, looked for a method of that name in its class and ancestors, and found none. It raises NoMethodError, at runtime. The receiver exists: it is the message it doesn't understand.

Que veut dire « undefined method 'x' for nil » ?What does "undefined method 'x' for nil" mean?

Le receveur est nil. Une variable ou un retour de méthode que l'on croyait être un objet métier vaut nil, et nil ne connaît pas x. Il faut remonter à l'endroit où la valeur est devenue nil, pas ajouter la méthode à nil.The receiver is nil. A variable or method result you thought was a domain object is nil, and nil doesn't know x. Trace back to where the value became nil rather than adding the method to nil.

Que vaut self en Ruby ?What is self in Ruby?

L'objet courant, celui qui reçoit les appels sans receveur écrit. Dans une méthode d'instance, c'est l'instance ; au niveau du script, c'est un objet appelé main (de classe Object).The current object, the one that receives calls with no written receiver. Inside an instance method it is the instance; at script level it is an object called main (of class Object).

1 + 2 est-il vraiment un appel de méthode ?Is 1 + 2 really a method call?

Oui. 1 + 2 est du sucre syntaxique pour 1.+(2) : le message + est envoyé à l'objet 1, qui le résout dans la classe Integer. Les deux écritures renvoient 3 avec Ruby 3.4.Yes. 1 + 2 is syntactic sugar for 1.+(2): the + message is sent to the object 1, which resolves it in the Integer class. Both forms return 3 on Ruby 3.4.

Quelle différence entre un appel avec et sans receveur ?What's the difference between a call with and without a receiver?

Sans receveur, Ruby envoie le message à self. miauler et self.miauler appellent la même méthode ; la seconde forme n'est requise que pour certains cas (comme les écritures d'attributs, self.nom = x).With no receiver, Ruby sends the message to self. miauler and self.miauler call the same method; the explicit form is only required in some cases (such as attribute writers, self.name = x).

RubyObjetsMessageselfNoMethodErrorModèle mental

← Tous les articlesAll articles