Jimi Damon wrote:
I am new to Ruby , but I consider this feature to be a bug.
What is happening is that i am creating a new Hash of Arrays. The
following code works fine
What is happening is that you create a Hash whose default value is one
Array.
a = Hash.new(Array.new())
a[:first] += [“this”]
a[:first] += [“is a”]
a[:first] += [“string”]
Here you are assigning a new array to a[:first] three times.
a = Hash.new(Array.new())
a[:key] += [“first”]
a[:key].push(“second”)
a[:key].push(“third”)
Here you are assigining a new array once and then changing it two times.
a = Hash.new(Array.new())
a[:key].push(“first”)
a[:key].push(“second”)
a[:key].push(“third”)
Here you are changing the default array three times.
However, this does not work if you don’t use the “+=” operator first.
+= isn’t one operator. It’s a shortcut for a[:key] = a[:key] +
[“first”].
This will first call the ±method on a a[:key] (i.e. it will call the +
method
on the default object because that’s what a[:key] points to at this
time),
which will return a new array, and then assign the resulting array to
a[:key]. This does not change the default array. Calling push would
because
the push method modifies its receiver while the + method doesn’t.
Note, this “feature” also
occurs for the “<<” operator , or any other methods that expect that
a[:key] is already a defined array.
No method expect any such thing. They don’t know or care about the hash
a. All
they care about is their arguments and their receiver. Since you call
them on
the hash’s default object, they will operate on the hash’s default
object.
I think if you already specified what the new object is going to be ,
then you should be able to call a method of that object.
I’m sorry, but I don’t follow. What new object? << and pop don’t create
any
new objects. And where did you specify what such an object would be?
Array#+
creates a new Array (unlike Array#<< and Array#pop, which just modify an
existing one), but it doesn’t do so, because you specified anywhere that
you
want an array. It does so because it always returns an array, because
that’s
what it’s been defined to do.