From: "Guy N. Hurst" Date: 2001-04-01T08:36:09+09:00 Subject: [ruby-talk:13400] Re: Multidimensional arrays and hashes? Lloyd Zusman wrote: > > Is it possible in ruby to make use of constructs that correspond to > the following Perl constructs? ... > > $array[1][2][3] = 'whatever'; # multidimensional array > > $hash{'a'}{'b'} = 'something'; # multidimensional hash > Since (unlike perl) variables are not typed, ruby has no way to auto-vivify the particular structure you have in mind. I mean, var could refer to a string, array, or hash. And var[2] could refer to an array or hash. (Hashes take any object as a key) So, no, you can't do it outright -- you have to initialize the variable as being an array or hash etc. first. array=[] array[1]=[] array[1][2]=[] array[1][2][3]='whatever' But maybe you wish to avoid clearing out the values if the arrays already partially exist? Use ||= to protect them. This way, a new array will only be assigned if it is currently nil; otherwise it will use the existing value. array||=[] array[1]||=[] array[1][2]||=[] array[1][2][3]='whatever' Now, this is somewhat lengthy. Here's a shorter way: (((array||=[])[1]||=[])[2]||=[])[3]='whatever' Of course, this all could backfire if an existing value is something other than an array... Also, this is pretty ugly, to be sure, but matz has said that he thinks it is a good practice to initialize first, anyway. However, he is also open to a new construct as follows: Hash.new{[]} cf. [ruby-talk:04256] In which case you'd be able to say hash=Hash.new{ {} } # default to a hash in this case hash['a']['b']='something' instead of: ((hash||={})['a']||={})['b']='something' However, I don't recall seeing the same thing being proposed for Array Guy N. Hurst -- HurstLinks Web Development http://www.hurstlinks.com/ Norfolk, VA 23510 (757)623-9688 FAX 623-0433 PHP/MySQL - Ruby/Perl - HTML/Javascript