From: "Ara.T.Howard" Date: 2005-10-14T01:41:54+09:00 Subject: Re: Iterate over md Array (the Ruby way) On Thu, 13 Oct 2005, Peter v. N. wrote: > Hi all, > > Once again I disturb you for a, maybe, obvious thing > I can't figure out. > > I have successfully created an md array (see older posts > from me) thanks to the support found here. > > Now I would like to list all String items in the source array > (a Text file containing numbers) and convert and place them into the > destination array as int objs. I know about the String#split method but this > recreates an array that does not match the dimensions I want > (e.g. lines with different length). > > My approach is very c-ish: > > > # @source is a String array. If the string contains a non-convertible > # substring, 0 is placed in destination array. @array is the destination # md > array created with the appropriate dimensions according to @source # (longest > line as vindex (-) and index as hindex (|) ) > > for i in 0...@hindex.length > for j in 0...@vindex[i].length > @array[i][j] = @source[i][j].to_i.char.to_i > end > end > > > Is there a Ruby way to replace with blocks? > > Thank you very much for a hint. > > Brgds, > Peter you want to be using narray i think: harp:~ > cat a.rb require 'narray' require 'stringio' sio = StringIO::new <<-txt 1 0 1 0 1 0 42 42 42 forty-two txt na = NArray::int 6, 3 j = 0 sio.each do |line| row = line.strip.split(%r/\s+/).map{|s| s.to_i} next if row.empty? row.each_with_index{|n,i| na[i,j] = n} j += 1 end p na 3.times{|row| puts "row #{ row } => #{ na[true, row].to_a.inspect }"} 6.times{|col| puts "col #{ col } => #{ na[col, true].to_a.inspect }"} harp:~ > ruby a.rb NArray.int(6,3): [ [ 1, 0, 1, 0, 1, 0 ], [ 42, 42, 42, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ] row 0 => [1, 0, 1, 0, 1, 0] row 1 => [42, 42, 42, 0, 0, 0] row 2 => [0, 0, 0, 0, 0, 0] col 0 => [1, 42, 0] col 1 => [0, 42, 0] col 2 => [1, 42, 0] col 3 => [0, 0, 0] col 4 => [1, 0, 0] col 5 => [0, 0, 0] cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | Your life dwells amoung the causes of death | Like a lamp standing in a strong breeze. --Nagarjuna ===============================================================================