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
