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.
That sounds like
Enumerable#mapIn fact, you don't even need the
each, sincemapis a method on anything that mixes inEnumerable.If you want to get a lazy enumerator, you can call
Enumerable#lazybefore applying any transformations. This returns an object on which all of theEnumerablemethods can be applied lazily.