From: Robert Klemme Date: 2011-03-25T16:48:34+09:00 Subject: Re: break from select On Fri, Mar 25, 2011 at 8:37 AM, Saravanan Krishnan wrote: > Hi venkat, > > Here is the better solution, > > a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] > b = [] > a.each do |x| >  next if b.length >= 5 >  b << x if x % 2 ==0 > end > > puts b You are still iterating the whole input Array. This is better irb(main):001:0> a = 1.upto(15).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] irb(main):002:0> b = [] => [] irb(main):003:0> a.each {|x| if x % 2 == 0; b << x; break if b.size >= 5 end} => nil irb(main):004:0> b => [2, 4, 6, 8, 10] Insert "p x" at beginning of block to see that we really short circuit. If you want to get fancy you can do this as well: irb(main):010:0> b = [] => [] irb(main):011:0> a.each {|x| p x; x % 2 == 0 and b << x and b.size >= 5 and break} 1 2 3 4 5 6 7 8 9 10 => nil We can even integrate this with #inject to get a *cough* one liner: irb(main):012:0> b = a.inject([]) {|c,x| p x; x % 2 == 0 and c << x and c.size >= 5 and break c or c} 1 2 3 4 5 6 7 8 9 10 => [2, 4, 6, 8, 10] :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/