From: "Ara.T.Howard" Date: 2005-08-20T04:41:16+09:00 Subject: Re: Ruby 2 Idea: You've got to have a[a][b][c][d][e][f][g][h][i]... On Sat, 20 Aug 2005, mathew wrote: > Xeno Campanoli wrote: >> There are just too many problems that can quickly be solved by >> multi-dimensional arrays and hashes not to have them and have them easily. >> I used the hack from "matz" today to make a 2d hash, and it's ugly and >> unworthy of Ruby. You should be able to do this without any extra steps >> just like in Perl. If the project ends up getting bigger THEN you refactor >> it, but YOU JUST GOT TO HAVE THAT. > > Well, the support for multiple dimensions of index selector is already there. > That is, you already have a[a][b][c][d][e][f][g][h][i]..., you just need to > create the array to start with. For that part, it's not too hard to write a > convenient multi-dimensional array factory method: > > require 'pp' > > def ArrayFactory(dimensions, initialvalue) > size = dimensions.first > if dimensions.length == 1 > return Array.new(size, initialvalue) > else > rest = dimensions[1,dimensions.length-1] > a = Array.new(size) > for i in 0..size > a[i] = ArrayFactory(rest, initialvalue) > end > return a > end > end > > a = ArrayFactory([3, 5, 7], "Hi!") > pp a > > a[2][3][7] = "Hello!" > puts a[2][3][7] > pp a[2][3] > > I have to say, though, that I've never had much need for multi-dimensional > arrays. Outside the realm of scientific data analysis, most of the time you > really want hashes because your "array" is sparse, has unusual bounds, or > whatever. At that point you should probably be looking at writing a proper > storage class. or use narray: harp:~ > cat a.rb require 'narray' na = NArray::byte 42, 42, 42 p na.size p na.shape na[] = 42 p na.min p na.max p na.mean.ceil na[] = 0 na[0 ... (na.size/2)] = 84 p na.min p na.max p na.mean.ceil harp:~ > time ruby a.rb 74088 [42, 42, 42] 42 42 42 0 84 42 real 0m0.020s user 0m0.020s sys 0m0.000s __fast__ -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 ===============================================================================