Hi there,
I was wondering if there was a way to 'restrict' an Enumerator in an elegant way.
Like a method like 'take' that returns another Enumerator instead of an Array.
The Point is not to instantiate a big, costly Array.
Example:
enum = Enumerator.new do |yielder|
n = 0
loop do
yielder << n
n += 1
end
end
# Take creates a new Array
enum.take(10) #=> [0,1,2,3,4,5,6,7,8,9]
# What it would be like with a enumerator restriction:
new_enum = enum.enum_take(10) #=> New Enumerator that wraps the old one
new_enum.to_a #=> [0,1,2,3,4,5,6,7,8,9]
# Possible implementation for enum_take
class Enumerator
def enum_take(ceiling)
Enumerator.new do |yielder|
index = 0
loop do
break if index > ceiling
yielder << self.next
index += 1
end
end
end
end
I made a little gist on github if anyone is interested: https://gist.github.com/Haniyya/f1541e7636e7d25ca2c1928a0b2df710 Thank you, Paul