From: Sam Roberts Date: 2004-03-19T23:49:03+09:00 Subject: Re: Can I stop each's iteration, and get the results so far? Wrote Robert Klemme , on Fri, Mar 19, 2004 at 05:59:36PM +0900: > > Basically, I want to break from a find_all, and get the array of > > elements found so far. Is this possible? > > > > I tried this, no luck with find_all and collect, they return nil, > > instead of the array so far. Any suggestions on how to do this? > > #inject is your friend: > > > puts "all n between 100 and 200?" > > > > p every.find_all { |n| break if n > 200; n >= 100 && n <= 200 } > > irb(main):076:0> every.inject([]) { |arr,n| break arr if n > 200; arr< if n >= 100 && n <= 200; arr } > => [102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, > 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, > 189, 192, 195, 198] Thanks, thats useful to know, and odd! Why can you break from inject and get the result, but not from find_all or collect? Is this a bug, an oversight, or is something about the methods that makes them need to be different? Cheers, Sam -- Sam Roberts