Trevor Harmon
4/30/2006 8:14:00 PM
Hi,
I'm new to Ruby and need a data structure that consists of a hashtable
of sets. While writing some code for this, I've run into some odd Ruby
behavior that I'm hoping someone can explain to me.
I started with a hashtable:
h = Hash.new([])
Here, I made the default value an empty set instead of nil. That way,
if I wanted to add a new element "q" to a set mapped to the key 'a', I
could do so in just one line. For example:
h['a'] = %w{q r s}
h['a'] << "t"
That seemed to work:
> h['a']
=> ["q", "r", "s", "t"]
> h['b']
=> []
Great! Now let me add an element to the set mapped to 'b':
h['b'] << "x"
That seemed to work, too:
> h['b']
=> ["x"]
But wait, now all the other keys are mapped to the same thing!
> h['c']
=> ["x"]
> h['d']
=> ["x"]
Can someone please explain how this happened? I don't understand it. Thanks,
Trevor
P.S. I'm using Ruby 1.8.4.