From: dblack@... Date: 2002-11-09T08:35:19+09:00 Subject: Re: Multi-dimensional (like 2) arrays in Ruby Hi -- On Sat, 9 Nov 2002, Ted wrote: > All of the replies say the same thing -- this is good. My learning > project for Ruby is implementing a turning grille cipher. I want to > allocate a n*m matrix where n and m are read from stdin. > > I have the n[] (the rows) array, no sweat. But the m part (the > columns) is rather elusive. There's a Matrix class shipped with Ruby -- have a look at lib/matrix.rb. > Here's my latest code: > > @m = Array.new(@rows) > @M = @m.each {|row| @m[row] = Array.new(@cols)} > > It doesn't work, either... :-( Don't forget that #each returns the receiver. In other words, in this: a = [1,2,3].each {|x| x * 20} a ends up as [1,2,3], not as [20,40,60]. The transformation is thrown away. In your example, you're trying to save the transformation explicitly to the array that's being transformed... but let Ruby do it for you :-) For that purpose, you can use #map. In fact, you can just map a series of arrays, based on the number of rows, directly into your matrix: m = (0...rows).map {|r| Array.new(cols)} Another way to do much the same thing is: m = [] rows.times { m << Array.new(cols) } David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav