masa / stars.gsfc.nasa.gov writes:

> Hi,
> 
> >From: Lloyd Zusman <ljz / asfast.com>
> 
> > 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
> > 
> > I know that I can create classes in ruby which encapsulate this
> > behavior, but before I re-invent the wheel, I'd like to know if anyone
> > has already come up with things like this in ruby.
> 
>   class ArrayMD < Array
>     def [](n)
>        self[n]=ArrayMD.new if super(n)==nil
>        super(n)
>     end
>   end
> 
>   a = ArrayMD.new
>   a[1][2][3]="foo"  #=> [nil, [nil, nil, [nil, nil, nil, "foo"]]]

Thank you very much.  And in the same spirit of your example, we can
do this with hashes, as well:

  class HashMD < Hash
    def [](n)
       self[n]=HashMD.new if super(n)==nil
       super(n)
    end
  end
  h = HashMD.new
  h['a']['b']['c'] = 'xxx'  #=>  {"a" => {"b" => {"c" => "xxx"}}}

However, both of these create empty containers (arrays, hashes)
whenever an access is made that points to a non-existent element:

  x = HashMD.new       #=>  {}
  item = x['a']['b']   #=>  {}
  x                    #=>  {"a" => {"b" => {}}}

[ Similar behavior with ArrayMD ]

In my opinion, in the ideal case, an attempt to access a non-existent
element should either yield `nil' or throw an exception, instead of
creating new structure and then returning an empty container.  But it
would require much more complexity in the code in order to give us
this behavior.

However, in many applications, this isn't a problem, in which case
the examples above would work just fine.


> See also  http://www.ir.isas.ac.jp/~masa/ruby/mdary.html
> 
> M.Tanaka

-- 
 Lloyd Zusman
 ljz / asfast.com