From: James Edward Gray II Date: 2006-11-27T00:40:10+09:00 Subject: Re: find index of first non zeo value in array On Nov 26, 2006, at 8:54 AM, Olivier wrote: > Le dimanche 26 novembre 2006 15:00, Josselin a �crit : >> 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 >> >> joss > > In that case, it is simpler to use an external counter, i think : > > c = 0 > array.each{|v| break if not v.zero?; c += 1} > puts c # => 15 You can ask Ruby to maintain the counter, if you want: >> require "enumerator" => true >> 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] => [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] >> result = array.enum_with_index.find { |n, i| n.nonzero? }.last rescue nil => 15 >> array.slice!(15, 1) => [21] >> array => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >> result = array.enum_with_index.find { |n, i| n.nonzero? }.last rescue nil => nil James Edward Gray II