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 Enumerableinclude EnumerableSuite.new(3).map { |x| x * 2 }
def each … # sans include Enumerable— La classe ne définit queeach. Appeler une méthode de la famille échoue :NoMethodError.The class only defineseach. Calling a method of the family fails:NoMethodError.include Enumerable— On inclutEnumerable: le module, qui s'appuie sureach, apporte toute la famille.We includeEnumerable: the module, built oneach, brings the whole family.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.
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) # => falseL’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 # => 1L’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) # => falseThe 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 # => 1Interpolation 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.