Created
September 20, 2016 13:09
-
-
Save Haniyya/f1541e7636e7d25ca2c1928a0b2df710 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
# As does take_while | |
enum.take_while{ |n| n <= 9 } #=> [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] | |
# The Same For take_while | |
new_enum = enum.enum_while { |n| n <= 9 } #=> New Enumerator | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment