Reply to comment

Ruby Hash can give odd behaviour (1.9.2)

 I guess I hadn't tried putting a default constructor in a Hash before, or if I had, the behaviour was different...

I wanted a Hash which holds a number of hashes (actually, to be honest, I probably just wanted it to have arrays, but when I started, I thought I wanted hashes, and it isn't an unreasonable use case).  I haven't worked out why this does what it does, 

irb(main):001:0> g=Hash.new({})
=> {}
irb(main):002:0> g[0]
=> {}
irb(main):003:0> g[1]
=> {}
irb(main):004:0> g[0][0]=1
=> 1
irb(main):005:0> g
=> {}
irb(main):006:0> g[0]
=> {0=>1}
irb(main):007:0> g[1]
=> {0=>1}

So the first four return values are what I expected.  I didn't expect g to be empty -surely it should be
{0=>{}, 1=>{}}
at that point? And I most definitely did not expect to see g[0] and g[1] returning the same value.

I get the same results (unsurprisingly) if I try g=Hash.new(Hash.new) too...
any ideas?


Trackback URL for this post:

http://www.parslow.net/brains/trackback/1657

Reply

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.