From: Joe Seeley Date: 2006-05-16T22:34:43+09:00 Subject: Re: 2 dimensional arrays Timothy Hunter wrote: > On May 15, 2006, at 5:06 PM, Joe Seeley wrote: > >> The 2 dimensional array or table structure is extremely common, but I >> don't see a simple/standard way to implement this in Ruby. Is >> there an >> easy way to do this? >> >> -- >> Posted via http://www.ruby-forum.com/. > > A 2-dimensional array is simply an array of arrays. Something like this: > > a = Array.new() {Array.new} > > Or you could use the Matrix class from "matrix" in the standard library. A 2 dimensional array as an array of arrays is a lowest common denominator. It assumes that I want only to use it as a simple storage mechanism. What I want is a 2 dimensional array data structure that has powerful operating mechanisms such as sorting. Additionally the way an array of arrays is treated in Ruby goes against what is intuitive or expected; and it was my understanding that Ruby was supposed to be designed to do what "least surprises". Here is a simple example. a = Array.new(){Array.new()} b = [9,8,7] c = [1,2,3] a[0] = b a[1] = c puts a.sort =>[[1,2,3],[9,8,7]] So this allows a sort across the entire array and it should be noted that it does an index step through comparison so [1,1,2] would come after [1,1,1]. However this means I am limited to sorting only via this mechanism. Based on Ruby syntax I would find this to be intuitive. a[0..1][0].sort The results I would then expect would be [[1],[9]] The results I actually get from this are [7,8,9] What is happening is that in a[0..1][0] a[0..1] is grabbing the subset of arrays 0 to 1 and then the second index [0] is indexing back in to the subset. What looks like it should be happening is that a[0..1][0] is defining the set of the arrays where we wish to retrieve the 0 index. -- Posted via http://www.ruby-forum.com/.