public
Last active

A sample partial implementation of a lazy enumerable. See http://gist.github.com/441028 for example usage.

  • Download Gist
lazy.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
module Lazy
module LazyEnumerable; end
 
class Enumerator
include LazyEnumerable
 
def initialize(enumerable=nil, &block)
if enumerable
@enumeration_block = proc {|send| enumerable.each(&send) }
else
@enumeration_block = block
end
end
 
def each(&block)
@enumeration_block.call(block)
end
end
 
module LazyEnumerable
def to_a
arr = []
self.each {|element| arr << element }
arr
end
 
def map(&block)
Enumerator.new do |send|
self.each do |element|
send.call block.call(element)
end
end
end
alias_method :collect, :map
 
def find_all(&block)
Enumerator.new do |send|
self.each do |element|
send.call(element) if block.call(element)
end
end
end
alias_method :select, :find_all
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.