T
Trevor Harmon
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:
Great! Now let me add an element to the set mapped to 'b':
h['b'] << "x"
That seemed to work, too:
But wait, now all the other keys are mapped to the same thing!
Can someone please explain how this happened? I don't understand it. Thanks,
Trevor
P.S. I'm using Ruby 1.8.4.
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:
=> ["x"]h['b']
But wait, now all the other keys are mapped to the same thing!
=> ["x"]h['c'] => ["x"]
h['d']
Can someone please explain how this happened? I don't understand it. Thanks,
Trevor
P.S. I'm using Ruby 1.8.4.