On Apr 29, 2008, at 3:46 PM, Victor Reyes wrote:

> Team,
>
> Given multi-dimension array @ga:
>
>    @ga = [
>            [0,0,0,0,1,9,0,4,0],
>            [0,0,4,8,0,0,6,0,0],
>            [7,5,0,0,0,0,0,0,2],
>            [0,9,0,1,0,2,0,0,4],
>            [0,0,0,0,0,3,0,0,0],
>            [5,0,0,4,0,6,0,3,0],
>            [8,0,0,0,0,0,0,7,3],
>            [0,0,6,0,0,8,4,0,0],
>            [0,1,0,2,9,0,0,0,0]
>            ]
>
> I am able to find then non-zero elements of a particular row:
>
> # If r = 0
>          rowArr = @ga[r]
>          puts rowArr
> # Output: 0 0 0 0 1 9 0 4 0
>
>          nonzeroElements = rowArr.find_all {|e| e > 0}
>          puts nonzeroElements                                       #
> Output: 1 9 4
>
> 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*
>
> Any help will be greatly appreciated, as usual!
>
> Thank you
>
> Victor



irb> require 'code/ruby/ext/enumerable.rb'
=> true
irb> @ga[0]
=> [0, 0, 0, 0, 1, 9, 0, 4, 0]
irb> @ga[0].map_with_index {|e,i| e.zero? ? nil : i}
=> [nil, nil, nil, nil, 4, 5, nil, 7, nil]
irb> @ga[0].map_with_index {|e,i| e.zero? ? nil : i}.compact
=> [4, 5, 7]

Then you just need Enumerable#map_with_index

module Enumerable
   # Like each_with_index, but the value is the array of block results.
   def map_with_index
     a = []
     each_with_index { |e,i| a << yield(e, i) }
     a
   end
end

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com