From: Robert Klemme Date: 2013-01-25T06:56:42+09:00 Subject: Re: Enum#select with max number of items On Thu, Jan 24, 2013 at 10:08 PM, masta Blasta wrote: > My premise is that i have a large array that i'd like to iterate with > select, but > I want up to a maximum (n) number of returns. Something like > Enum#select_first_n_matches. > > yes i could do my_arr.select{ blocky }.first(n). Which is a neat > one-liner, but has the performance overhead of iterating through the > entire array. > > is there a method that does this already? Anyone have any slick one-line > solutions? irb(main):003:0> 1_000_000.times.inject([]) {|a,x| a << x if x.odd?; break a if a.size >= 10; a} => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] irb(main):004:0> 1_000_000.times.inject([]) {|a,x| x.odd? and a << x and a.size >= 10 and break a; a} => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] > My working solution is: > new_arr = []; matches = 0 > my_arr.each do |ele| > if condition > new_arr << ele > matches += 1 > break if matches >= limit > end > end You can simplify that new_arr = [] my_arr.each do |ele| if condition new_arr << ele break if new_arr.size >= limit end end or new_arr = [] my_arr.each do |ele| condition and new_arr << ele and new_arr.size >= limit and break end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/