Search code examples
rubyenumerator

Ruby method to compose Enumerator with function


If you have an enumerator and some callable (proc/lambda/method) it is sometimes handy to compose them to create a new enumerator, like this

class Enumerator
  def compose func
    Enumerator.new do |yielder|
      each { |x| yielder << func[x] }
    end
  end
end

# make an enumerator that yields 0, 2, 4, 6...
(0..10).each.compose(proc { |x| x * 2 })

Is there no built-in method for doing this? Or no simpler syntax? I've been trawling the docs because we have Enumerator::+ and Proc::<< which are close but not quite right.


Solution

  • That sounds like Enumerable#map

    (0..10).each.map { |x| x * 2 }
    

    In fact, you don't even need the each, since map is a method on anything that mixes in Enumerable.

    (0..10).map { |x| x * 2 }
    

    If you want to get a lazy enumerator, you can call Enumerable#lazy before applying any transformations. This returns an object on which all of the Enumerable methods can be applied lazily.

    (0..10).lazy.map { |x| x * 2 }