Chris Moline <ugly-daemon / home.com> writes:

> Hi, I was wondering why do we have to do this
> 
> array = []
> 
> before we can assign to an array. I was thinking I would like it to
> behave like it does in perl where it automatically creates an array
> when you do something like this
> 
> array[0][1] = 3

Except... :)

In Ruby, you really have no idea that

   a[1] = 2

is an array assignment. For example

   class Dave
     attr :value
     def []=(n, val)
       @value = val * n
     end
   end

   d = Dave.new

   d[2] = "foo"

   p d.value   #=>  "foofoo"

   d[3] = 7
   d.value     #=>  21


Of course, no one would actually write something as heinous as the
above, but the possibility still exists. And the '[]' methods _are_
used quite frequently in other classes:

  % ri []
  The method named `[]' is not unique among Ruby's classes and modules:
     Array#[], Array::[], Bignum#[], Dir::[], Fixnum#[], Hash#[],
     Hash::[], MatchData#[], Method#[], Proc#[], String#[], Struct#[],
     Thread#[]

However, I belive that we will soon have a slightly different (and
more powerful) form of auto-vivification, where you'll be able to
write the viviver code (?) yourself.


Regards


Dave