Created
December 8, 2010 04:32
-
-
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.
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
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