From: Robert Klemme Date: 2010-08-28T04:20:06+09:00 Subject: Re: how about Array#collect_until On 27.08.2010 21:08, timr wrote: > Thanks everyone for the great ideas. I ended up slightly modifying > Senault's suggestion (see below), though I learned from all the > various approaches. In my particular case I do need an inclusive > collect (long story, but using this to do some DNA fuzzy expression > matching that smartly knows when it has found a good solution and > breaks rather than finishing all the other possible calculations, and > I need to see the solution). And though the inject is a great > suggestion, I would prefer keeping the code blocks for determining > endpoint grammatically separated from the processing block, rather > than embedded. > Arigato Ruby Community, > Tim > > #collects items processed through block until a solution satisfies the > function test (lambda{}) > class Array I would rather place this code in Enumerable. Then all other classes mixing in this module will benefit. > def collect_until(fn,&block) > results = [] > self.each do |x| Why does everybody write "self.each" when "each" is sufficient? > result = (yield x) > results<< result > break if fn.call(result) As far as I can see this is not in line with your original requirement because in your original posting you evaluated the termination condition on the original value while this code does it on the result of the mapping calculation. If you change that you don't need to store "result". You can also use "return" instead of "break" here for a more immediate exit: return results if fc[x] > end > results > end > end > p %w[ find out if that this but not the other mother > mouth].collect_until(lambda {|word| word[-2,2] == 'st' }){|item| item > + "t" } > > puts "another attempt" > > p [1,6,7,5,3,0,10,12,14].collect_until(Proc.new {|num| num> 25 }){| > item| item * 4 } > > puts "another attempt" > p [1,2,3].collect_until(Proc.new {|x| x%2 == 0}) {|item| item + 10} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/