From: Stefano Cobianchi Date: 2007-08-04T05:50:00+09:00 Subject: Re: Running multiple closures per iteration 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 } -- S.