From: Joel VanderWerf Date: 2006-05-28T04:31:27+09:00 Subject: Re: Basic ruby looping question Joel VanderWerf wrote: > Marston A. wrote: ... >> for row in @large_row_array WHERE row.element == "something" >> ... some some stuff >> end ... > So as long as you are working with tests that can be expressed using > #===, you can use #grep. In your case, grep may not be so useful after all. You would have to define an object whose #=== method performs the row.element == "something" test. require 'benchmark' tester = Object.new def tester.===(row) row.element == 987654 end class Row attr_accessor :element end rows = (0..1_000_000).map {|i| r = Row.new; r.element = i; r} Benchmark.bmbm do |b| b.report("grep") do rows.grep(tester) {|row|} end b.report("each-if") do rows.each {|row| if row.element == 987654 then nil end } end b.report("select-each") do rows.select {|row| row.element == 987654}.each {|row|} end end __END__ Rehearsal ----------------------------------------------- grep 0.720000 0.000000 0.720000 ( 0.725553) each-if 0.590000 0.000000 0.590000 ( 0.587160) select-each 0.770000 0.000000 0.770000 ( 0.768704) -------------------------------------- total: 2.080000sec user system total real grep 0.730000 0.000000 0.730000 ( 0.735809) each-if 0.590000 0.000000 0.590000 ( 0.587350) select-each 0.570000 0.000000 0.570000 ( 0.564276) -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407