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} > > Such a combination is useful when iterating through a collection is > expensive, e.g. on a large file on a slow disk. Did you mean o = a.select {|x| x >= 0} p = o.inject(0) {|s, x| s += x} ^^^ ? Then you can do this: a = [1,-1,2,-2,3,-3] sp = a.inject(0) {|s, x| x >= 0 ? s + x : s} p sp # ==> 6 (note that += is not needed, + is good enough) But there is no way in general to combine two iterations. -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407