This stems from a fundamental misunderstanding of how the default
attribute of a hash is used by the hash.
On Sun, Mar 12, 2006 at 08:26:05AM +0900, Javier V. wrote:
} Look this:
}
} tigre@enigma tigre $ irb
} irb(main):001:0> events = {}
} => {}
The events variable has been set to a new instance of a hash.
} irb(main):002:0> events.default = []
} => []
The events.default attribute has been set to a new instance of an array.
} irb(main):003:0> events[“trying”] << “hello”
} => [“hello”]
The array in the events.default attribute is retrieved, since “trying”
is
not a key in the hash, and has “hello” appended to it.
} irb(main):004:0> events
} => {}
The events variable continues to hold an empty hash, which has a default
attribute set to [“hello”].
} irb(main):005:0> events.inspect
} => “{}”
Still empty.
} irb(main):006:0> events[“trying”]
} => [“hello”]
The events.default attribute is retrieved since “trying” is not a key in
the hash. The attribute is an array which has previously had “hello”
appended to it.
} why is happening this behaviour?
This is correct behavior. The default attribute is not the default
starting
value for any key, it is the value returned when a key is not found. See
the following:
irb(main):001:0> events = {}
=> {}
irb(main):002:0> events.default = []
=> []
irb(main):003:0> events[“trying”] << “hello”
=> [“hello”]
irb(main):004:0> events[“nosuchkey”]
=> [“hello”]
irb(main):005:0> events.default
=> [“hello”]
irb(main):006:0> events.default.object_id
=> 403034172
irb(main):007:0> events[“trying”].object_id
=> 403034172
irb(main):008:0> events[“nosuchkey”].object_id
=> 403034172