From: dblack@... Date: 2007-08-04T05:52:53+09:00 Subject: Re: Running multiple closures per iteration Hi -- On Sat, 4 Aug 2007, Stefano Cobianchi wrote: > On Aug 3, 7:38 pm, Joshua Chia wrote: >> Is there a way to run more than one closure per iteration through a >> collection? For example, if I want to do the following two things, can >> I combine them so that I only end up with one pass over the collection, >> without doing a manual for loop? >> >> o = a.select {|x| x >= 0} >> p = a.inject(0) {|s, x| s += x} > > btw, you don't need the += operator here: > a.inject(0) {|s, x| s + x} > => 6 > >> Such a combination is useful when iterating through a collection is >> expensive, e.g. on a large file on a slow disk. > > o = 0; p = [] > a.each { |x| o << x if x >= 0; p += x } a.each { |x| p << x if x >= 0; o += x } :-) David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)