From: "David A. Black" Date: 2008-04-30T05:37:46+09:00 Subject: Re: Getting array index for non-zero elements Hi -- On Wed, 30 Apr 2008, Siep Korteling wrote: > Rob Biedenharn wrote: >> On Apr 29, 2008, at 3:46 PM, Victor Reyes wrote: >> >>> [5,0,0,4,0,6,0,3,0], >>> # Output: 0 0 0 0 1 9 0 4 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 > > It works without the 'require' here.(VERSION=1.8.6). I like the > map_with_index method (new for me), but isn't it overkill here? > > @ga.each do |sub_arr| > sub_arr.each_with_index do |value,index| > print index.to_s + " " unless value == 0 > end > puts > end If all you need is side-effects, like printing, then you can used #each (with_ or without index). #map_with_index, like #map itself, returns a second collection. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!