L'objet Method : le modèle mental de l'instantané contre le message en Ruby The Method object: the mental model of snapshot versus message in Ruby

obj.method(:m) donne un objet Method, un instantané figé de l'implémentation. Envoyer le message ré-résout à chaque appel. Animation et Ruby 3.4.obj.method(:m) gives a Method object, a frozen snapshot of the implementation. Sending the message re-resolves on every call. Animation and Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
MétaprogrammationMetaprogramming
PubliéPublished

En bref. Une méthode n’est pas une valeur qu’on transporte. Pour en avoir une, on la demande : on obtient un objet Method, qui fige l’implémentation du moment.

Le modèle en une phrase

Un objet Method est un instantané. Envoyer le message ré-résout à chaque appel.

In short. A method isn’t a value you carry around. To get one you ask for it: you get a Method object, which freezes the implementation of that moment.

The model in one sentence

A Method object is a snapshot. Sending the message re-resolves on every call.

m = c.method(:miaule)
class Chat; def miaule = "MIAOU"; end
m.call
c.miaule # ou c.send(:miaule)
Méthode ou messageMethod or messagehandle capturéhandle capturéChat (la classe, maintenant)Chat (the class, now)miaule → "miaou"m (objet Method, figé)m (Method object, frozen)miaule → "miaou"ré-résolu à l'appelre-resolved on callversion capturéecaptured versiontirets = valeur figée, détachée de la classedashes = frozen value, detached from the classvérifié avec Ruby 3.4checked with Ruby 3.4
  1. m = c.method(:miaule) — c.method(:miaule) demande la méthode : on obtient un objet Method qui garde l'implémentation du moment.c.method(:miaule) asks for the method: you get a Method object holding the implementation of that moment.
  2. class Chat; def miaule = "MIAOU"; end — On redéfinit la méthode dans la classe. Le handle, lui, n'a pas bougé.We redefine the method in the class. The handle hasn't moved.
  3. m.call — Le handle rend l'ancienne version : c'est un instantané.The handle returns the old version: it's a snapshot.
  4. c.miaule # ou c.send(:miaule) — Envoyer le message ré-résout à chaque appel : on obtient la version actuelle.Sending the message re-resolves on every call: you get the current version.
Un objet Method est un instantané de l'implémentation au moment de la capture. Envoyer le message ré-résout à chaque appel. Toute la différence entre une méthode et un message tient là.A Method object is a snapshot of the implementation at capture time. Sending the message re-resolves on every call. That is the whole difference between a method and a message.

La preuve, avec Ruby 3.4

class Chat; def miaule = "miaou"; end
c = Chat.new
m = c.method(:miaule)

class Chat; def miaule = "MIAOU"; end

p m.call            # => "miaou"
p c.miaule          # => "MIAOU"
p c.send(:miaule)   # => "MIAOU"

Le handle n’a pas suivi la redéfinition, le message oui.

Passer une méthode comme un bloc

p [1, 2, 3].map(&10.method(:+))   # => [11, 12, 13]

Détacher la méthode

um = Chat.instance_method(:miaule)
p um.class                  # => UnboundMethod
p um.bind(Chat.new).call    # => "MIAOU"

L’erreur, telle que Ruby l’écrit

c.method(:vole)
undefined method 'vole' for class 'Chat' (NameError)

Ce que l’image cache

Un handle capturé tôt peut garder un comportement périmé sans qu’aucune erreur ne le signale. Si tu veux « la version actuelle », envoie le message. Si tu veux une version précise, garde le Method, en sachant ce qu’il fige.

Pour aller plus loin

Le numéro ci-dessous détaille l’objet Method, l’instantané et le message, avec des exercices.

The proof, with Ruby 3.4

class Chat; def miaule = "miaou"; end
c = Chat.new
m = c.method(:miaule)

class Chat; def miaule = "MIAOU"; end

p m.call            # => "miaou"
p c.miaule          # => "MIAOU"
p c.send(:miaule)   # => "MIAOU"

The handle didn’t follow the redefinition, the message did.

Passing a method as a block

p [1, 2, 3].map(&10.method(:+))   # => [11, 12, 13]

Detaching the method

um = Chat.instance_method(:miaule)
p um.class                  # => UnboundMethod
p um.bind(Chat.new).call    # => "MIAOU"

The error, as Ruby writes it

c.method(:vole)
undefined method 'vole' for class 'Chat' (NameError)

What the picture hides

A handle captured early can keep a stale behaviour without any error flagging it. If you want “the current version”, send the message. If you want a precise version, keep the Method, knowing what it freezes.

Go deeper

The issue below details the Method object, the snapshot and the message, with exercises.

Questions fréquentesFrequently asked questions

Comment obtenir une méthode comme valeur en Ruby ?How do I get a method as a value in Ruby?

Définir une méthode ne donne pas de valeur : il faut la demander avec obj.method(:nom), qui renvoie un objet Method appelable avec call.Defining a method doesn't give a value: you have to ask for it with obj.method(:name), which returns a Method object callable with call.

Que se passe-t-il si la méthode est redéfinie ensuite ?What happens if the method is redefined afterwards?

L'objet Method garde l'ancienne implémentation : m.call rend « miaou » même si c.miaule rend désormais « MIAOU ».The Method object keeps the old implementation: m.call returns “miaou” even though c.miaule now returns “MIAOU”.

Quelle différence entre Method et message ?What's the difference between a Method and a message?

Un message (c.miaule, c.send(:miaule)) est résolu à chaque appel. Un objet Method est résolu une fois, à la capture.A message (c.miaule, c.send(:miaule)) is resolved on every call. A Method object is resolved once, at capture.

À quoi sert &obj.method(:m) ?What is &obj.method(:m) for?

À passer une méthode là où on attend un bloc : [1, 2, 3].map(&10.method(:+)) donne [11, 12, 13].To pass a method where a block is expected: [1, 2, 3].map(&10.method(:+)) gives [11, 12, 13].

Qu'est-ce qu'un UnboundMethod ?What is an UnboundMethod?

Une méthode détachée de tout objet, obtenue par Classe.instance_method(:m). On la rattache avec bind(objet) avant de l'appeler.A method detached from any object, obtained with Class.instance_method(:m). You attach it with bind(object) before calling it.

RubyMethodsendMessageModèle mental

← Tous les articlesAll articles