ActiveSupport::HashWithIndifferentAccess integer

So I noticed that hash with indifferent access is not indifferent to integers as keys.

Currently this doesn’t work.

hash = HashWithIndifferentAccess.new({“1” =>3})
hash[1] # => 3

``

The specific use case for me was passing around ids from the browser which was necessary because the form was using dynamic fields generated from database records, like a form with questions stored in the database.

We could make hashes with indifferent access truly indifferent which would help this particular use case. I’m not sure what type of existing code this would break, but I’m interested to learn what issues there would be with this feature. What do y’all think of this idea?

I can’t really speak to the usefulness of this, but I think you’ll meet resistance due it being a breaking change.

HashWithIndifferentAccess allows other types of keys; it just doesn’t convert the key to string, as it does with symbols.

Current behavior:

hash = HashWithIndifferentAccess.new({“1” => 3, 1 => ‘a’, nil => ‘b’})

hash[‘1’] # => 3

hash[:‘1’] # => 3

hash[1] # => ‘a’

hash[nil] # => ‘b’

So, if you started performing the conversion for integers too, you’d break any code that relies on the current integer behavior.

In the docs, HashWithIndifferentAccess is defined as “Implements a hash where keys :foo and ‘foo’ are considered to be the same.” That’s simple and easy to reason about.

If you start down this path with integers, you’re opening the door to unforeseen complexity. And why stop at integers? I’ve had cases where it would be convenient for UUID’s to be treated “indifferently” also. I’m not really trying to argue slippery slope, just saying there are other scenarios where it could be useful to expand the indifference but that quickly makes this class much harder to reason about.

But maybe integers are special enough and the breaking change minimal enough to make it worthwhile.

-Al