ActiveSupport::HashWithIndifferentAccess integer

36 views
Skip to first unread message

m...@charliemassry.com

unread,
Sep 21, 2015, 8:11:19 PM9/21/15
to Ruby on Rails: Core
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?

Al Tenhundfeld

unread,
Sep 21, 2015, 10:31:01 PM9/21/15
to rubyonra...@googlegroups.com
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


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages