From: x1 Date: 2006-11-28T16:35:10+09:00 Subject: Re: find index of first non zeo value in array Just saw this.. @ ruby conf, there were talks about the speed of ruby's regex Being that ruby was the first language I picked up, I'm curious as to how other languages(such as perl) compare from a performance standpoint with your examples. I'm not expecting perl to be slower an any scenerio, but is the perl index() quicker or slower than a perl regex? If the latter, is the performance ratio proportional to that of our ruby examples? On 11/27/06, Tim Pease wrote: > On 11/27/06, William James wrote: > > > > William James wrote: > > > Robert Klemme wrote: > > > > On 26.11.2006 14:59, Josselin wrote: > > > > > with : > > > > > array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, > > > > > 0, 0, 0, 0, 0] > > > > > > > > > > I wrote : > > > > > array.index(array.detect {|x| x > 0}) => 15 > > > > > > > > > > is there a better and simpler way to do it ? > > > > > thanks > > > > > > > > Did we have a solution with #inject already? > > > > > > array.inject(0){|i,e| if e>0; break i else i+1 end} > > > > array.inject(0){|i,e| break i if e>0; i+1 } > > > > Using a regular expression ... > > array.join =~ /[^0]/ > > The inject method is faster, though, because you do not have to create > a string. I'm assuming that the "array.index((array-[0])[0])" solution > suffers from the same problem -- creating another object under the > covers ... > > $ ruby tmp.rb > user system total real > inject 2.874000 0.000000 2.874000 ( 2.884000) > index 0.721000 0.000000 0.721000 ( 0.731000) > regexp 3.755000 0.000000 3.755000 ( 3.765000) > > Wow! Looks like the "index" method wins hands down. > > But mine is still shorter ;) > > TwP > >