Hash.new{...} bug?

Hello ruby-talk,

i think i found bug in “ruby 1.7.2 (2002-07-02) [i386-mswin32]”

hash = Hash.new{Hash.new}
hash[0][0] = 1
p hash[0] #=> {}

i think it must print “{0=>1}”. and it actually printed when i use "hash = Hash.new(Hash.new)"
as first line or manual initialization:

hash = {}
hash[0] = {}
hash[0][0] = 1
p hash[0] #=> {0=>1}

what say ruby 1.7.3?

···


Best regards,
Bulat mailto:bulatz@integ.ru

Hi,

···

At Wed, 18 Dec 2002 22:20:50 +0900, Bulat Ziganshin wrote:

i think i found bug in “ruby 1.7.2 (2002-07-02) [i386-mswin32]”

hash = Hash.new{Hash.new}
hash[0][0] = 1
p hash[0] #=> {}

i think it must print “{0=>1}”.

Hash ‘default’ proc never modify the hash itself automatically.
Try with this.

hash = Hash.new {|h,k| h[k] = Hash.new}


Nobu Nakada

Hello nobu,

Wednesday, December 18, 2002, 4:47:39 PM, you wrote:

hash = Hash.new{Hash.new}
Hash ‘default’ proc never modify the hash itself automatically.
Try with this.

hash = Hash.new {|h,k| h[k] = Hash.new}

thanks. but with Hash.new(…) hash element updated to default value.
is this difference intended?

···


Best regards,
Bulat mailto:bulatz@integ.ru

thanks. but with Hash.new(…) hash element updated to default value.
is this difference intended?

No there is a difference …

···

“Bulat Ziganshin” bulatz@integ.ru wrote


hash = Hash.new {Hash.new}
hash[‘a’][‘b’] = ‘c’
hash[‘a’][‘b’] = ‘c’

ObjectSpace.each_object(Hash) {|hsh|
puts ([hsh.id, hsh.inspect].join (": "))
}

20728500: {“b”=>“c”}
20728824: {“b”=>“c”}
20729328: {}

/Christoph

Bulat Ziganshin wrote:

Hello nobu,

Wednesday, December 18, 2002, 4:47:39 PM, you wrote:

hash = Hash.new{Hash.new}

Hash ‘default’ proc never modify the hash itself automatically.
Try with this.

hash = Hash.new {|h,k| h[k] = Hash.new}

thanks. but with Hash.new(…) hash element updated to default value.
is this difference intended?

What difference to you mean?

h1 = Hash.new(7)
h2 = Hash.new{7}

p h1[3]
p h2[3]

p h1
p h2

Output:
7
7
{}
{}

Hi,

hash = Hash.new{Hash.new}
Hash ‘default’ proc never modify the hash itself automatically.
Try with this.

hash = Hash.new {|h,k| h[k] = Hash.new}

thanks. but with Hash.new(…) hash element updated to default value.
is this difference intended?

In the first style you wrote, the returned value is updated but
discarded soon. The last style, the default value is updated
as same but kept in the hash and reused.

`Default value’ may need operator assignments to work well.

h = Hash.new(0)
h[0] += 1
h[:foo] += 2
p h # {0=>1, :foo=>2}

class Hash
def <<(arg)
if Hash === arg
update(arg)
else
store(*arg)
end
self
end
end
h = Hash.new {{}}
h[:foo] <<= [:bar, 1]
h[:zot] <<= {:baz=>2}
p h # {:zot=>{:baz=>2}, :foo=>{:bar=>1}}

···

At Wed, 18 Dec 2002 22:54:59 +0900, Bulat Ziganshin wrote:


Nobu Nakada