Skip to content

Instantly share code, notes, and snippets.

@Haniyya
Created September 20, 2016 13:09
Show Gist options
  • Save Haniyya/f1541e7636e7d25ca2c1928a0b2df710 to your computer and use it in GitHub Desktop.
Save Haniyya/f1541e7636e7d25ca2c1928a0b2df710 to your computer and use it in GitHub Desktop.
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