From: Matthew Moss Date: 2006-05-16T23:38:27+09:00 Subject: Re: 2 dimensional arrays > 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. Aside from a 1-dimensional array using flattened indices, an array of arrays is the most basic and common mechanism, because memory is 1-dimensional. Show me a computer with 2-dimensional memory and I'll write you a better structure. > 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". I think most people find the array of arrays to be fairly intuitive (i.e. first index selects a subarray, second index selects an item from the subarray), and Ruby holds to that intuition. I would nonoffensively suggest that what you are expecting is non-intuitive. > 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. You are limited to that sorting mechanism only if you choose to be; try using sort_by and use your own code to determine sort order. > 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] a[0..1] grabs the 0th and 1st item of a. However, in order to return multiple values, Ruby uses arrays, so those go right back into an array. Then you use [0], and get back the 0th item [7,8,9]. Pretty straightforward. To get the results you want is not terribly difficult: a.collect { |x| [x[0]] } Yes, I've also heard that Ruby is intended to be a language of "least surprises", but you can satisfy everyone at the same time. However, it is also a language of easy extendability, so if an array of arrays does not serve your purposes, or you have a different interpretation of the [] operator, it's trivial to start fleshing out your own classes to make it a language of "least surprises for you". class Array2D def [] (i) # ... end def []= (i, x) # ... end end