3

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.

1 Answer 1

4

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 }
Sign up to request clarification or add additional context in comments.

2 Comments

enum.lazy.map(&:func) is specifically what I needed since I want to keep it as an enumerator. Thanks!
@Max Enumerator::produce might also be of interest e.g. enum = Enumerator.produce(0) {|prev| prev + 2} then enum.take(10) #=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.