From: Robert Klemme Date: 2008-08-13T01:57:33+09:00 Subject: Re: Exiting .each early On 12.08.2008 18:51, Myrddin Emrys wrote: > I want to return part of a sorted array efficiently. The built in > iterators will search the entire array, but since I know it's sorted, I > only need to collect the items up until they stop being in range. > However, its pretty wasteful to keep iterating after they start to fall > out of range... > > How do I break a .each (or .collect, .reject, etc) early? Exactly with break. :-) irb(main):001:0> (1..10).each {|i| p i; break if i > 5} 1 2 3 4 5 6 => nil > Is there a simple way to do this? A rather complex solution would be to > create a routine to find the index where the transition from valid to > invalid occurred, and slice the array to that index... but just being > able to iterate over half of the items (rather than all) would be > efficient enough for me at this point. I rather suggest to use binary search. There is a library in RAA that does it. Maybe there's also a gem. Kind regards robert