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 + 21.+(2)# => 3
1 + 2— Il n'y a pas d'opérateur câblé :1 + 2s'écrit aussi1.+(2). Le receveur est l'objet1, le message est+, l'argument est2.There is no wired-in operator:1 + 2can also be written1.+(2). The receiver is the object1, the message is+, the argument is2.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— La méthode s'exécute et renvoie3. Rien de spécial pour les nombres : c'est le même mécanisme que pour n'importe quel objet.The method runs and returns3. Nothing special about numbers: it's the same mechanism as for any object.
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 # => ObjectLes 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.zzzundefined 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, ouuser&.nomqui renvoienilau 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 # => ObjectThe 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.zzzundefined 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, oruser&.name, which returnsnilinstead 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.