Enumerable : le modèle mental du contrat minimal d'un seul each en Ruby Enumerable: the mental model of the minimal one-each contract in Ruby

Écris un seul each qui yielde, include Enumerable, et tu hérites de plus de soixante méthodes. Le mixin n'a pas d'autre source que ton each. Ruby 3.4.Write a single each that yields, include Enumerable, and you inherit over sixty methods. The mixin has no source other than your each. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
EnumerableEnumerable
PubliéPublished

En bref. Le contrat d’Enumerable est minimal : un each qui yielde. Tout le reste en découle.

Le modèle en une phrase

Un seul each, un include Enumerable, et le mixin appelle ton each : il n’a aucune autre source.

In short. The Enumerable contract is minimal: an each that yields. Everything else follows.

The model in one sentence

A single each, one include Enumerable, and the mixin calls your each: it has no other source.

def each; yield 3; yield 1; yield 2; end
include Enumerable
t.map { _1 * 2 }
t.select(&:odd?) ; t.reduce(:+)
Un each, soixante méthodesOne each, sixty methodseach seuleach seulTrio#eachyield 3yield 1yield 2×0Enumerablemapselectreducesortminmax×N = nombre d'appels à ton each ; hachuré = pas encore mixé×N = calls to your each; hatched = not mixed in yetvérifié avec Ruby 3.4checked with Ruby 3.4
  1. def each; yield 3; yield 1; yield 2; end — Un seul each qui yielde les éléments. Sans include, map n'existe pas : NoMethodError.A single each that yields the elements. Without include, map doesn't exist: NoMethodError.
  2. include Enumerable — Une ligne, et tu hérites d'une soixantaine de méthodes : map, select, reduce, sort…One line, and you inherit around sixty methods: map, select, reduce, sort…
  3. t.map { _1 * 2 } — map n'a pas d'autre source que ton each : il l'appelle, et collecte.map has no other source than your each: it calls it, and collects.
  4. t.select(&:odd?) ; t.reduce(:+) — Chaque méthode relance each depuis le début : trois appels, trois parcours.Each method restarts each from the top: three calls, three passes.
Implémente un seul each qui yielde tes éléments, include Enumerable, et tu hérites d'une soixantaine de méthodes. Le mixin appelle ton each : il n'a aucune autre source.Implement a single each that yields your elements, include Enumerable, and you inherit around sixty methods. The mixin calls your each: it has no other source.

La preuve, avec Ruby 3.4

class Trio
  include Enumerable
  def each
    yield 3; yield 1; yield 2
    self
  end
end

t = Trio.new
p t.map { _1 * 2 }   # => [6, 2, 4]
p t.select(&:odd?)   # => [3, 1]
p t.reduce(:+)       # => 6
p t.sort             # => [1, 2, 3]
p t.min, t.max       # => 1, 3

L’erreur, telle que Ruby l’écrit

class Sans; def each; yield 1; end; end
Sans.new.map { _1 }
undefined method 'map' for an instance of Sans (NoMethodError)

Avoir un each ne suffit pas : c’est include Enumerable qui apporte map.

Chaque méthode relance each

Avec un compteur dans each, après map, select, reduce, sort, min et max, il vaut 6, puis 7 après first, qui s’arrête dès le premier élément.

Ce que l’image cache

Le contrat est minimal, pas gratuit : comme chaque méthode relance each, une structure dont le parcours coûte cher le paiera à chaque appel. Et réécrire map ou select à la main est presque toujours inutile.

Pour aller plus loin

Le numéro ci-dessous détaille le contrat each / Enumerable, avec des exercices.

The proof, with Ruby 3.4

class Trio
  include Enumerable
  def each
    yield 3; yield 1; yield 2
    self
  end
end

t = Trio.new
p t.map { _1 * 2 }   # => [6, 2, 4]
p t.select(&:odd?)   # => [3, 1]
p t.reduce(:+)       # => 6
p t.sort             # => [1, 2, 3]
p t.min, t.max       # => 1, 3

The error, as Ruby writes it

class Sans; def each; yield 1; end; end
Sans.new.map { _1 }
undefined method 'map' for an instance of Sans (NoMethodError)

Having an each isn’t enough: it’s include Enumerable that brings map.

Each method restarts each

With a counter inside each, after map, select, reduce, sort, min and max, it reads 6, then 7 after first, which stops at the first element.

What the picture hides

The contract is minimal, not free: since each method restarts each, a structure whose traversal is expensive pays for it on every call. And rewriting map or select by hand is almost always unnecessary.

Go deeper

The issue below details the each / Enumerable contract, with exercises.

Questions fréquentesFrequently asked questions

Que faut-il implémenter pour utiliser Enumerable ?What do I have to implement to use Enumerable?

Une seule méthode : each, qui yielde chaque élément. Puis include Enumerable. Le mixin construit tout le reste à partir de elle.A single method: each, yielding each element. Then include Enumerable. The mixin builds everything else from it.

Combien de méthodes Enumerable apporte-t-il ?How many methods does Enumerable provide?

Soixante et une en Ruby 3.4 (Enumerable.instance_methods.size) : map, select, reduce, sort, min, max, first, include?, count, sum…Sixty-one in Ruby 3.4 (Enumerable.instance_methods.size): map, select, reduce, sort, min, max, first, include?, count, sum…

Que se passe-t-il sans include Enumerable ?What happens without include Enumerable?

map n'existe pas : NoMethodError, undefined method 'map' for an instance of Sans. Avoir un each ne suffit pas, il faut mixer le module.map doesn't exist: NoMethodError, undefined method 'map' for an instance of Sans. Having an each isn't enough, you must mix the module in.

Chaque méthode parcourt-elle la structure depuis le début ?Does each method walk the structure from the start?

Oui, chacune rappelle each. Ici, map, select, reduce, sort, min et max appellent each six fois, plus une pour first, qui s'arrête tôt.Yes, each one calls each again. Here map, select, reduce, sort, min and max call each six times, plus one for first, which stops early.

Faut-il réécrire map et select soi-même ?Should I rewrite map and select myself?

Non, c'est le piège : réécrire ces méthodes une à une duplique du code que le mixin fournit déjà, testé et complet.No, that's the trap: rewriting these methods one by one duplicates code the mixin already provides, tested and complete.

RubyEnumerableeachMixinModèle mental

← Tous les articlesAll articles