From: "David A. Black" Date: 2004-03-19T23:58:42+09:00 Subject: Re: Can I stop each's iteration, and get the results so far? Hi -- On Fri, 19 Mar 2004, Sam Roberts wrote: > 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? I think the idea of breaking from find_all is sort of contradictory, since it runs counter to the "all" part of "find_all" :-) But anyway... what Robert does is "break arr" -- that is, he gives break an argument. That argument then becomes the return value of the whole thing. You can't do that with find_all, because you don't have direct access to the accumulator ("arr" in Robert's example). David -- David A. Black dblack@wobblini.net