Skip to content

Instantly share code, notes, and snippets.

@kerinin
Created March 14, 2014 00:55
Show Gist options
  • Save kerinin/9540261 to your computer and use it in GitHub Desktop.
Save kerinin/9540261 to your computer and use it in GitHub Desktop.
# Basics - if you define an enumerable, you can evaluate it lazily
class Foo
include Enumerable
def each(&block)
(1..20).to_a.each do |i|
yield i
puts "yielded #{i}"
end
end
end
Foo.new.lazy.take(10).to_a # => [1,2,3,4,5,6,7,8,9,10]
# Notice that #take will only return the number of elements you allow in #each
class Foo
include Enumerable
def each(&block)
(1..5).to_a.each do |i|
yield i
puts "yielded #{i}"
end
end
end
Foo.new.lazy.take(10).to_a # => [1,2,3,4,5]
# So let's do something crazy - we're going to put a non-terminating loop
# inside our #each implementation and see what happens (hint: it's awesome)
class Foo
include Enumerable
def each(&block)
@counter ||= 1
loop do
yield @counter
@counter += 1
end
end
end
Foo.new.lazy.take(10).to_a # => [1,2,3,4,5,6,7,8,9,10]
# And we can still terminate one some condition
class Foo
include Enumerable
def each(&block)
@counter ||= 1
while @counter <= 5 do
yield @counter
@counter += 1
end
end
end
Foo.new.lazy.take(10).to_a # => [1,2,3,4,5]
# Ruby is awesome; QED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment