Skip to content

Instantly share code, notes, and snippets.

@BFalkner
Created December 8, 2010 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BFalkner/732887 to your computer and use it in GitHub Desktop.
Save BFalkner/732887 to your computer and use it in GitHub Desktop.
A sample partial implementation of a lazy enumerable. See http://gist.github.com/441028 for example usage.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment