From: "David A. Black" Date: 2008-11-02T04:30:06+09:00 Subject: Re: Iterator objects and lazy evaluation Hi -- On Sun, 2 Nov 2008, Brian Candler wrote: > Yuh-Ruey Chen wrote: >> 1) Are there equivalents for iteration/enumeration functions like map >> that return iterator/enumeration objects (in a Python sense)? > > You can generate Enumerator objects, and in 1.9 (and I think 1.8.7), an > Enumberable method which hasn't been given a block returns an > Enumerator. > > irb(main):001:0> a = (1..10).each > => # > irb(main):002:0> a.next > => 1 > irb(main):003:0> a.next > => 2 > irb(main):004:0> a.next > => 3 > > However I don't think you can use these for chaining. It might be nice > if you could do something like > > (1..10).to_enum.map2 { |x| x * 2 }.map2 { |x| x + 1 }.map2 { |x| puts > x } > > which wouldn't create any intermediate array. I guess you'd need each > element to call 'next' on the previous one, and you'd need something at > the end to trigger the whole process off. It used to be that you could associate a block with an enumerator lazily: >> e = [1,2,3].enum_for(:map,&lambda {|x| x * 10 }) => # >> e.next => 10 and some chaining was possible. But that's gone now. Enumerators are still able to remember regular arguments, though, so you can do: > e = [1,2,3,4,5].each_cons(2) => # >> e.select {|a,b| b > 3 } => [[3, 4], [4, 5]] (The contrast here is between a relatively old 1.9 version and 1.9.1 preview 1.) David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!