Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix lookup on HashWithIndifferentAccess for array values. #3811

Closed
wants to merge 1 commit into from

Conversation

zetter
Copy link
Contributor

@zetter zetter commented Nov 30, 2011

Currently HashWithIndifferentAccess has some odd behaviour that differs from Hash.

The problem:
Accessing a HashWithIndifferentAccess does not return the the same object that is stored in the hash (i.e. equal?) causing unexpected results:

hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
hash[:a] << 1  # => [1]
hash[:a]       # => [], expected [1]

The cause:
When a block is provided to generate default values the generated values are duped if they are arrays. The duped value is stored in the hash but the original value is returned when the hash is accessed.

My fix:
The duping is there for allowing frozen arrays containing hashes to be modified. My fix restricts the duping to this case. Note that if default function generates a frozen array an error will be raised on assignment before and after my patch.

@nashby
Copy link
Contributor

nashby commented Apr 7, 2012

👍 /cc @fxn

@@ -153,7 +153,8 @@ def convert_value(value)
if value.is_a? Hash
value.nested_under_indifferent_access
elsif value.is_a?(Array)
value.dup.replace(value.map { |e| convert_value(e) })
value = value.dup if value.frozen?
value.replace(value.map { |e| convert_value(e) })

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could just use value.map! instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants