From: "Ara.T.Howard" Date: 2004-04-21T11:34:07+09:00 Subject: Re: efficient collect+compact ? On 21 Apr 2004, Martin Pirker wrote: > Hello... > > What's the most efficient way for > > puts [1,2,3,4,5,6,7,8,9,10].collect{ |x| next if x % 2 == 0; x+10 }.compact > or > puts [1,2,3,4,5,6,7,8,9,10].collect!{ |x| next if x % 2 == 0; x+10 }.compact! > > Or: > I want to iterate over all array elements, process them, decide > whether the result is any good, and keep only the good ones. > It's ok doing that by chaining collect+compact, but I ponder this must > be slow/inefficient for array with xxxxx elements. doesn't seem to make much difference: ~ > time ruby -e '(1..ARGV.shift.to_i).to_a.collect{|x| next if x % 2 == 0; x+10 }.compact' 1048576 real 0m1.496s user 0m1.480s sys 0m0.020s ~ > time ruby -e '(1..ARGV.shift.to_i).to_a.collect!{ |x| next if x % 2 == 0; x+10 }.compact!' 1048576 real 0m1.396s user 0m1.390s sys 0m0.000s suprising. > I read Array and Enumerable docs, have I missed something[1] or does > a straight "collect everything but nil" function not exist? > > Martin > > [1] > (it's already past 3am but I remember searching the same thing sometime ago) > -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | URL :: http://www.ngdc.noaa.gov/stp/ | TRY :: for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done ===============================================================================