Search code examples
rubyenumerator

When is an enumerator useful?


An Enumerator object can be created by calling certain methods without passing a block, for example Array#reject:

(1..3).reject.to_a
# => [1, 2, 3]

Is this just some rule of ruby for easier chaining or is there some other way to pass behavior to the Enumerator?


Solution

  • Is this just some rule of ruby for easier chaining

    Yes, this reason exactly. Easy chaining of enumerators. Consider this example:

    ary = ['Alice', 'Bob', 'Eve']
    
    records = ary.map.with_index do |item, idx|
      {
        id: idx,
        name: item,
      }
    end
    
    records # => [{:id=>0, :name=>"Alice"}, {:id=>1, :name=>"Bob"}, {:id=>2, :name=>"Eve"}]
    

    map yields each element to with_index, which slaps item index on top of it and yields to your block. Block returns value to with_index, which returns to map which (does its thing, the mapping, and) returns to caller.