« undefined method 'map' » : le modèle mental des protocoles implicites en Ruby "undefined method 'map'": the mental model of implicit protocols in Ruby

Ruby attend certains messages sans jamais les déclarer : each, <=>, to_s. Fournis le hook, inclus le module, et une famille entière de méthodes arrive. Animation et sorties réelles de Ruby 3.4.Ruby expects certain messages without ever declaring them: each, <=>, to_s. Provide the hook, include the module, and a whole family of methods arrives. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
Duck typingDuck typing
PubliéPublished

En bref. Le duck typing dit « réponds au message », mais lesquels ? Ruby en attend certains sans les déclarer. Tu fournis un seul hook (each, <=>), tu inclus le module, et tu récupères toute une famille de méthodes.

Le modèle en une phrase

Un hook contre une famille : l’interface existe, mais personne ne l’a écrite.

In short. Duck typing says “answer the message”, but which ones? Ruby expects some without declaring them. You provide a single hook (each, <=>), include the module, and get a whole family of methods back.

The model in one sentence

One hook for a family: the interface exists, but nobody wrote it.

def each … # sans include Enumerable
include Enumerable
Suite.new(3).map { |x| x * 2 }
Un hook contre une familleOne hook for a familyhook : eachhook: eachta classeyour classdef each—la famille de méthodesthe method familymapselectfirstsorthors jeu : NoMethodErrorout of play: NoMethodErrorrésultat : result: —vérifié avec Ruby 3.4checked with Ruby 3.4
  1. def each … # sans include Enumerable — La classe ne définit que each. Appeler une méthode de la famille échoue : NoMethodError.The class only defines each. Calling a method of the family fails: NoMethodError.
  2. include Enumerable — On inclut Enumerable : le module, qui s'appuie sur each, apporte toute la famille.We include Enumerable: the module, built on each, brings the whole family.
  3. Suite.new(3).map { |x| x * 2 } — Même appel, cette fois ça marche : [2, 4, 6]. Un hook contre une famille de méthodes.Same call, now it works: [2, 4, 6]. One hook for a family of methods.
Protocoles implicites en Ruby : définis le hook (each, <=>), inclus le module, et toute une famille de méthodes arrive.Implicit protocols in Ruby: define the hook (each, <=>), include the module, and a whole family of methods arrives.

La preuve, avec Ruby 3.4

class Suite
  def initialize(n) = @n = n
  def each
    @n.times { |i| yield i + 1 }
  end
end

s = Suite.new(3)
p s.respond_to?(:map)   # => false

L’erreur, telle que Ruby l’écrit

s.map { |x| x * 2 }
undefined method 'map' for an instance of Suite (NoMethodError)

Un include plus tard

class Suite; include Enumerable; end

p s.map { |x| x * 2 }   # => [2, 4, 6]
p s.select(&:odd?)      # => [1, 3]
p s.include?(2)         # => true
p s.first(2)            # => [1, 2]
p s.sort.reverse        # => [3, 2, 1]

Une seule méthode écrite, each, et la classe parle comme un tableau.

Les autres protocoles

class Pt
  def initialize(x) = @x = x
  def to_s = "Pt(#{@x})"
end
puts "voici #{Pt.new(4)}"   # => voici Pt(4)

class Cm
  include Comparable
  attr_reader :v
  def initialize(v) = @v = v
  def <=>(o) = v <=> o.v
end
p Cm.new(1) < Cm.new(2)               # => true
p [Cm.new(3), Cm.new(1)].min.v        # => 1

L’interpolation appelle to_s ; Comparable s’appuie sur <=>.

Ce que l’image cache

Le dessin montre deux protocoles. Il y en a d’autres (hash et eql? pour les clés de Hash, to_str, coerce…), et chaque hook a ses règles : <=> doit renvoyer nil quand deux objets ne se comparent pas, et each doit faire yield de chaque élément.

Pour aller plus loin

Le numéro ci-dessous parcourt les protocoles les plus utiles avec des exercices.

The proof, with Ruby 3.4

class Suite
  def initialize(n) = @n = n
  def each
    @n.times { |i| yield i + 1 }
  end
end

s = Suite.new(3)
p s.respond_to?(:map)   # => false

The error, as Ruby writes it

s.map { |x| x * 2 }
undefined method 'map' for an instance of Suite (NoMethodError)

One include later

class Suite; include Enumerable; end

p s.map { |x| x * 2 }   # => [2, 4, 6]
p s.select(&:odd?)      # => [1, 3]
p s.include?(2)         # => true
p s.first(2)            # => [1, 2]
p s.sort.reverse        # => [3, 2, 1]

One method written, each, and the class talks like an array.

The other protocols

class Pt
  def initialize(x) = @x = x
  def to_s = "Pt(#{@x})"
end
puts "voici #{Pt.new(4)}"   # => voici Pt(4)

class Cm
  include Comparable
  attr_reader :v
  def initialize(v) = @v = v
  def <=>(o) = v <=> o.v
end
p Cm.new(1) < Cm.new(2)               # => true
p [Cm.new(3), Cm.new(1)].min.v        # => 1

Interpolation calls to_s; Comparable relies on <=>.

What the picture hides

The drawing shows two protocols. There are others (hash and eql? for Hash keys, to_str, coerce…), and each hook has its rules: <=> must return nil when two objects can’t be compared, and each must yield every element.

Go deeper

The issue below walks through the most useful protocols with exercises.

Questions fréquentesFrequently asked questions

Qu'est-ce qu'un protocole implicite en Ruby ?What is an implicit protocol in Ruby?

Un ensemble de méthodes que Ruby ou un module attend d'un objet sans que ce soit déclaré : each pour Enumerable, <=> pour Comparable, to_s pour l'interpolation. Pas d'interface écrite, seulement une convention.A set of methods that Ruby or a module expects from an object without it being declared: each for Enumerable, <=> for Comparable, to_s for interpolation. No written interface, only a convention.

Que faut-il pour qu'une classe ait map et select ?What does a class need to get map and select?

Définir each (qui fait yield de chaque élément) et inclure Enumerable. Le module construit map, select, first, sort, include? et bien d'autres à partir de each.Define each (which yields each element) and include Enumerable. The module builds map, select, first, sort, include? and many more on top of each.

Que donne Comparable ?What does Comparable give?

Si la classe définit <=> et inclut Comparable, elle obtient <, <=, ==, >, >=, between? et clamp, et ses objets deviennent triables avec min, max et sort.If the class defines <=> and includes Comparable, it gets <, <=, ==, >, >=, between? and clamp, and its objects become sortable with min, max and sort.

Que se passe-t-il si j'oublie d'inclure Enumerable ?What happens if I forget to include Enumerable?

Définir each ne suffit pas : map lève NoMethodError (undefined method 'map' for an instance of ...). C'est l'inclusion du module qui apporte la famille.Defining each isn't enough: map raises NoMethodError (undefined method 'map' for an instance of ...). Including the module is what brings the family.

Comment connaître le protocole attendu par une méthode ?How do I know which protocol a method expects?

Dans la documentation du module ou de la méthode : Enumerable précise qu'il faut each, Comparable qu'il faut <=>. L'interpolation de chaîne appelle to_s.In the module's or method's documentation: Enumerable states it needs each, Comparable that it needs <=>. String interpolation calls to_s.

RubyProtocolesEnumerableComparableModèle mental

← Tous les articlesAll articles