Project

General

Profile

Actions

Bug #18688

closed

when array's default value is empty hash adding a hash key value changes all array elements

Added by pan (Pan Pan) over 2 years ago. Updated over 2 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]
[ruby-core:108204]

Description

ah = Array.new(3, {})
ah[1][:foo] = 'bar'
p ah # [{:foo=>"bar"}, {:foo=>"bar"}, {:foo=>"bar"}]

This is not expected result. The expected result is [{}, {:foo=>"bar"}, {}].
Alternatively, below code works as expected.

ah = Array.new(3) {{}}
ah[1][:foo] = 'bar'
p ah # [{}, {:foo=>"bar"}, {}]

Updated by jeremyevans0 (Jeremy Evans) over 2 years ago

  • Status changed from Open to Rejected

This is expected behavior and not a bug. As you mentioned, you want to use the block form if you want a new object for each default value.

Actions

Also available in: Atom PDF

Like0
Like0