From: Brian Candler Date: 2008-11-04T22:23:53+09:00 Subject: Re: Iterator objects and lazy evaluation Actually, it turns out you don't even need ruby-1.9 for this. The following runs fine in ruby-1.8.6: module Enumerable class Gen include Enumerable def initialize(&body) @body = body end def each(&receiver) @body.call(receiver) end end def filter(&blk) Gen.new do |y| each do |*input| blk.call(y, *input) end end end end (1..10). filter { |y,e| puts "Sending #{e.inspect}"; y[e]; puts "Sent" }. filter { |y,e| y[e] if e % 2 == 0; sleep 0.5 }. filter { |y,e| y[e + 100]; sleep 0.5 }. each { |e| puts e } The puts and sleep calls are in there to show this is proper 'horizontal' evaluation, with no intermediate arrays. But if you want an array of the finished product, just replace the last line with "to_a" I wouldn't be surprised if this pattern exists in a library somewhere, but I don't know where. -- Posted via http://www.ruby-forum.com/.