liveBook · Manning

Enum_for

As explained in The Well-Grounded Rubyist, Fourth Edition

enum_for, also known as to_enum, is a Ruby method that creates an Enumerator attached to a specified method of an object, optionally supplying arguments to that method.

enum_for, also called to_enum, creates an Enumerator whose each method is attached to a method on another object. The target defaults to :each, but any yielding method can be selected. The Enumerator acts as a front end to that method, obtaining values by triggering its yields. section 10.9.2

Supply the target method and, when needed, arguments for that method:

  • names.enum_for(:select) creates an Enumerator whose each delegates to names.select. section 10.9.2
  • names.enum_for(:inject, "Names: ") permanently stores the argument and passes it to inject whenever iteration runs. section 10.9.2
  • Stored mutable arguments can create side effects: appending with << changes the same string across repeated iterations, whereas string addition creates a new string. section 10.9.2
  • The Enumerator's Enumerable methods are based on its own each, so they can differ from methods overridden by the original object. section 10.10.1

Delegating to Hash methods

h = { cat: "feline", dog: "canine", cow: "bovine" } e = h.enum_for(:select) e.each { |key, value| key =~ /c/ } #=> { cat: "feline", cow: "bovine" } e = h.to_enum e.select { |key, value| key =~ /c/ } #=> [[:cat, "feline"], [:cow, "bovine"]] The first Enumerator delegates each to Hash#select, preserving its hash result. The second defaults to Hash#each; its select is Enumerable#select and therefore returns an array. section 10.10.1

names = %w(David Black Yukihiro Matsumoto)
e = names.enum_for(:select)

Inspect a minimal enum_for(:select) Enumerator before applying its each method. section 10.9.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains delegation, default and explicit target methods, forwarded arguments, mutable state, and overridden Enumerable behavior.
Examples
Uses arrays, hashes, select, inject, map, and repeated iteration to expose delegation and side effects.
What it assumes
Assumes familiarity with blocks, each, Enumerable methods, and object-specific method overrides.
What you can do after
Apply enum_for or to_enum to attach iteration to a chosen method and pass it stable or carefully managed arguments.
How it connects
Links Enumerator with each, Enumerable, select, inject, map, and Hash method behavior.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.