From: Phrogz Date: 2006-11-28T14:05:04+09:00 Subject: Re: find index of first non zeo value in array Devin Mullins wrote: > James Edward Gray II wrote: > > I believe there has been talk in the past of having index() take a > > block for matching. > Meh... talk schmalk... > > class Array > alias orig_index index > def index(*args) > return orig_index(*args) unless block_given? > (0...length).each do |i| > return i if yield self[i] > end > nil > end > end Hrm, I assumed that using #each_with_index would be speedier, since there would be no Ruby call to the #[] method of the array for each iteration. Instead, it's much slower: class Array alias orig_index index def index1(*args) return orig_index(*args) unless block_given? (0...length).each do |i| return i if yield self[i] end nil end def index2( *args ) return orig_index(*args) unless block_given? each_with_index{ |value,index| return index if yield value } nil end end require 'benchmark' N = 1000 a = (1..1000).to_a Benchmark.bmbm{ |x| x.report( '0...length' ){ N.times{ |i| a.index1{ |v| v==i } } } x.report( 'each_with_i' ){ N.times{ |i| a.index2{ |v| v==i } } } } #=> Rehearsal ----------------------------------------------- #=> 0...length 2.060000 0.030000 2.090000 ( 2.333379) #=> each_with_i 3.340000 0.050000 3.390000 ( 3.727040) #=> -------------------------------------- total: 5.480000sec #=> #=> user system total real #=> 0...length 2.060000 0.020000 2.080000 ( 2.286168) #=> each_with_i 3.350000 0.040000 3.390000 ( 3.716824)