Project

General

Profile

Actions

Bug #20442

closed

Printing class variable inconsistent when using nested hashes

Added by k776 (Kieran Pilkington) 8 months ago. Updated 8 months ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:117640]

Description

See attached test.rb. I have a class with a class variable. The idea is simple, increment the value and then print out the resulting class var.

Mock1
0
1

Mock2
{}
{"a"=>1}

Mock3
{}
{"a"=>1}

Mock4
{}
{}

Mock1 through Mock3 are working as expected. But Mock4 does not, it outputs a blank hash, rather than the expected: {"a"=>{"a"=>1}}

The value is being set. If I replace the print method with @val['a']['a'] is outputs the number 1 as expected.


Files

test.rb (820 Bytes) test.rb k776 (Kieran Pilkington), 04/22/2024 06:05 AM

Updated by jeremyevans0 (Jeremy Evans) 8 months ago

  • Status changed from Open to Rejected

Not a bug. For the behavior you want, in Mock4

  @val = Hash.new{|h, k| h[k] = Hash.new(0)}

With @val = Hash.new(Hash.new(0)), the @val['a'] expression returns the Hash.new(0) default value, but does not set a value in @val.

Actions

Also available in: Atom PDF

Like0
Like0