map, select, reduce : le modèle mental des transformations en Ruby map, select, reduce: the mental model of transformations in Ruby

map transforme, select filtre, reduce replie, each_with_object bâtit. Une chaîne nomme l'intention étape par étape — mais chaîner pour chaîner est un piège. Ruby 3.4.map transforms, select filters, reduce folds, each_with_object builds. A chain names the intent step by step — but chaining for its own sake is a trap. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
EnumerableEnumerable
PubliéPublished

En bref. Une boucle qui accumule cache son intention dans la mécanique ; une chaîne la nomme.

Le modèle en une phrase

Chaque maillon prend une collection et en rend une nouvelle : select filtre, map transforme, reduce replie.

In short. A loop that accumulates hides its intent in the mechanics; a chain names it.

The model in one sentence

Each link takes a collection and returns a new one: select filters, map transforms, reduce folds.

n = [1, 2, 3, 4, 5, 6]
n.select(&:even?)
.map { _1 * 10 }
.reduce(:+)
Penser en transformationsThinking in transformations6 valeurs6 valeursdépartselectmapreduce123456chaque étape rend une nouvelle valeur, le tableau d'origine ne bouge paseach step returns a new value, the original array doesn't changevérifié avec Ruby 3.4checked with Ruby 3.4
  1. n = [1, 2, 3, 4, 5, 6] — Le point de départ : six entiers.The starting point: six integers.
  2. n.select(&:even?) — select filtre : il garde, il ne change aucune valeur.select filters: it keeps, it changes no value.
  3. .map { _1 * 10 } — map transforme : autant de valeurs en sortie qu'en entrée.map transforms: as many values out as in.
  4. .reduce(:+) — reduce replie la liste en une seule valeur : 120.reduce folds the list into a single value: 120.
Chaque maillon prend une collection et en rend une nouvelle : select filtre, map transforme, reduce replie. Une chaîne nomme l'intention étape par étape.Each link takes a collection and returns a new one: select filters, map transforms, reduce folds. A chain names the intent step by step.

La preuve, avec Ruby 3.4

n = [1, 2, 3, 4, 5, 6]
p n.select(&:even?).map { _1 * 10 }.reduce(:+)   # => 120
p n.map { _1 * 2 }                               # => [2, 4, 6, 8, 10, 12]
p n.select(&:odd?)                               # => [1, 3, 5]
p n.each_with_object({}) { |x, h| h[x] = x * x }
# => {1 => 1, 2 => 4, 3 => 9, 4 => 16, 5 => 25, 6 => 36}
p n.map { _1 }.equal?(n)                         # => false

Les pièges qui mordent

p [].reduce(:+)      # => nil   (pas de valeur initiale)
p [].reduce(0, :+)   # => 0
p [].sum             # => 0

Et si un mot suffit, écris-le : n.find { _1 > 3 } rend 4, %w[a b a c a].tally rend {"a" => 3, "b" => 1, "c" => 1}.

Ce que l’image cache

La chaîne a un coût : chaque maillon crée un tableau intermédiaire. Et chaîner pour chaîner nuit : si tu jettes le résultat d’un map, tu voulais each.

Pour aller plus loin

Le numéro ci-dessous détaille map, select, reduce et each_with_object, avec des exercices.

The proof, with Ruby 3.4

n = [1, 2, 3, 4, 5, 6]
p n.select(&:even?).map { _1 * 10 }.reduce(:+)   # => 120
p n.map { _1 * 2 }                               # => [2, 4, 6, 8, 10, 12]
p n.select(&:odd?)                               # => [1, 3, 5]
p n.each_with_object({}) { |x, h| h[x] = x * x }
# => {1 => 1, 2 => 4, 3 => 9, 4 => 16, 5 => 25, 6 => 36}
p n.map { _1 }.equal?(n)                         # => false

The traps that bite

p [].reduce(:+)      # => nil   (no initial value)
p [].reduce(0, :+)   # => 0
p [].sum             # => 0

And if one word is enough, write it: n.find { _1 > 3 } returns 4, %w[a b a c a].tally returns {"a" => 3, "b" => 1, "c" => 1}.

What the picture hides

The chain has a cost: each link builds an intermediate array. And chaining for its own sake hurts: if you throw away a map’s result, you wanted each.

Go deeper

The issue below details map, select, reduce and each_with_object, with exercises.

Questions fréquentesFrequently asked questions

Quelle est la différence entre map, select et reduce ?What is the difference between map, select and reduce?

map transforme chaque élément (même nombre en sortie), select filtre (garde ou écarte), reduce replie toute la collection en une seule valeur.map transforms each element (same count out), select filters (keeps or drops), reduce folds the whole collection into a single value.

Quand utiliser each_with_object plutôt que reduce ?When should I use each_with_object instead of reduce?

Pour bâtir une structure (hash, tableau) : l'objet accumulateur est passé tel quel, sans avoir à le rendre à chaque tour, contrairement à reduce.To build a structure (hash, array): the accumulator object is passed as-is, with no need to return it each turn, unlike reduce.

map modifie-t-il le tableau d'origine ?Does map modify the original array?

Non, il rend un nouveau tableau (n.map { _1 }.equal?(n) vaut false). Seules les variantes en ! modifient le receveur.No, it returns a new array (n.map { _1 }.equal?(n) is false). Only the bang variants modify the receiver.

Que rend reduce(:+) sur un tableau vide ?What does reduce(:+) return on an empty array?

nil. Pour éviter la surprise, donne une valeur initiale : [].reduce(0, :+) rend 0, tout comme [].sum.nil. To avoid the surprise, give an initial value: [].reduce(0, :+) returns 0, just like [].sum.

Faut-il toujours chaîner ses transformations ?Should I always chain my transformations?

Non : si tu jettes le résultat d'un map, tu voulais each ; si un mot suffit (find, tally, sum), écris-le plutôt qu'une chaîne.No: if you throw away a map's result, you wanted each; if one word is enough (find, tally, sum), write it instead of a chain.

RubymapselectreduceModèle mental

← Tous les articlesAll articles