Skip to content

Instantly share code, notes, and snippets.

@zbelzer
Created March 13, 2012 17:58
Show Gist options
  • Save zbelzer/2030293 to your computer and use it in GitHub Desktop.
Save zbelzer/2030293 to your computer and use it in GitHub Desktop.
Lazy enumerable?
class Lazy
include Enumerable
def initialize(max_iterations=nil, &block)
@max_iterations = max_iterations
@iterations = 0
@block = block
end
def each
while @max_iterations.nil? || @iterations < @max_iterations
@last = @block.call(@last)
yield @last
@iterations += 1
end
end
end
l = Lazy.new(100) do |x|
(x || 0) + 1
end
l.each {|x| puts x; break if x > 50}
puts l.to_a.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment