Sebastian Hungerecker
12/8/2007 10:52:00 AM
Jimi Damon wrote:
> Bernardo Rufino wrote:
> > In addition, to create different Arrays objects use a block...
> >
> > irb(main):001:0> a = Hash.new{|hash, key| hash[key] = Array.new;}
> > => {}
> > irb(main):002:0> a[:first]
> > => []
> > irb(main):003:0> a[:first] << "test"
> > => ["test"]
>
> Yes, but if you run this example and type "a" you get
>
> irb(main):003:0> a
> => {}
This is not true.
>> a = Hash.new{|hash, key| hash[key] = Array.new}
=> {}
>> a[:first] << "test"
=> ["test"]
>> a
=> {:first=>["test"]}
> I'm sorry...but I think this is incorrect... You have defined an array
> as being the default type , hence after
> you have performed << "test" , a should contain
>
> => {:first=>["test"]}
>
> But it does not..
Yes, it does. See above.
> When you define Hash.new( ) , this is the default value when you HAVE
> NOT defined the key for that value.
>
> Hence, if I do
>
> a = Hash.new("tmp")
>
> and type in irb
> irb(main):006 a = Hash.new("tmp")
> => {}
> irb(main):007 a[:first]
> => "tmp"
> irb(main):008 a
> => {}
> irb(main):009
>
> This makes sense because it is accessing the default value for the key
> which is "tmp"
Exactly.
> However, with that being said, if my default type is an "array", then I
> should be able to Push into that array a value and have it stay around,
If you push an item into the default array. It does stay around. The array
doesn't get assigned to the key, but the item stays in the array. See:
>> h = Hash.new(Array.new)
=> {}
>> h[:bla]
=> []
>> h[:bla] << "la"
=> ["la"]
>> h[:bla]
=> ["la"]
>> h[:blubb]
=> ["la"]
>> h
=> {}
After the first line the default item is an empty array. h[:bla] will give you
this array. Calling << on it, will put "la" into the array. The default item
is now ["la"]. It is not assigned to any hash key, but everytime you get the
default item, this is what you will get.
> other wise why does
> a[:key] += ["value"]
> and then
> a[:key].push("another value")
> work ?
As I explained in my previous post the first line expands to:
a[:key] = a[:key] + ["value"]
This will first evaluate a[:key] + ["value"].
This calls the + method on the default array with ["value"] as an argument.
What the method does is it creates a new array containing all the items of the
default array as well as the items of the argument. Assuming the default
array was empty before, this will evaluate to the array ["value"] (without
changing the default array). So the expression now reads
a[:key] = ["value"]
This assigns the new array ["value"] to a[:key]. a[:key] now no longer points
to the default array. As such calling push on it, no longer calls push on the
default array, but on the new array it points to.
HTH,
Sebastian
--
NP: Explosions in the Sky - A Poor Man's Memory
Jabber: sepp2k@jabber.org
ICQ: 205544826