From: Stefano Crocco Date: 2008-04-30T05:11:22+09:00 Subject: Re: Getting array index for non-zero elements On Tuesday 29 April 2008, Victor Reyes wrote: > However, I don't actually want the elements, I would like to get the index > of those non-zero elements. I tried the following but it fails: > >           nonzeroIndex = rowArr.index rowArr.find_all {|e| e > 0} >           puts > nonzeroIndex                                                          # > Output: *nil* Array#find_all returns an array containing all the elements for which the block returns true. Since this array is not a member of rowArr, rowArr.index returns nil. The simplest way to achieve what you want, in my opinion, is the following: require 'enumerator' rowArr.enum_for(:each_index).find_all{|i| rowArr[i] > 0} This creates an Enumerator (see ri Enumerator and ri enum_for) whose 'each' method calls rowArr.each_index instead rowArr.each. The block is thus passed the index of the elements instead of the elements themselves, and the array returned by findAll will contain the indexes of the items greater than 0. I hope this helps Stefano