Created
March 13, 2012 17:58
-
-
Save zbelzer/2030293 to your computer and use it in GitHub Desktop.
Lazy enumerable?
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
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