This blog is part of our Rails 6 series.
Rails 6 added support of symbol keys with ActiveSupport::HashWithIndifferentAccess#assoc.
Please note that documentation of ActiveSupport::HashWithIndifferentAccess#assoc in Rails 5.2 shows that ActiveSupport::HashWithIndifferentAccess#assoc works with symbol keys but it doesn't.
In Rails 6, ActiveSupport::HashWithIndifferentAccess implements a hash where string and symbol keys are considered to be the same.
Before Rails 6, HashWithIndifferentAccess#assoc used to work with just string
keys.
Let's checkout how it works.
Let's create an object of
ActiveSupport::HashWithIndifferentAccess
and call assoc on that object.
>> info = { name: 'Mark', email: '[email protected]' }.with_indifferent_access
=> {"name"=>"Mark", "email"=>"[email protected]"}
>> info.assoc(:name)
=> nil
>> info.assoc('name')
=> ["name", "Mark"]
We can see that assoc does not work with symbol keys with
ActiveSupport::HashWithIndifferentAccess
in Rails 5.2.
Now, let's call assoc on the same hash in Rails 6 with both string and symbol
keys.
>> info = { name: 'Mark', email: '[email protected]' }.with_indifferent_access
=> {"name"=>"Mark", "email"=>"[email protected]"}
>> info.assoc(:name)
=> ["name", "Mark"]
>> info.assoc('name')
=> ["name", "Mark"]
As we can see, assoc works perfectly fine with both string and symbol keys
with
ActiveSupport::HashWithIndifferentAccess
in Rails 6.
Here is the relevant pull request.

Related blogs
- 01Rails 6 adds support to persist timezones of Active JobSeptember 1, 2020 · Chetan Gawai
- 02Rails 6 adds including & excluding method on EnumerablesAugust 18, 2020 · Akhil Gautam
- 03Rails 6 fixes after_commit callback invocation bugFebruary 25, 2020 · Amit Choudhary
- 04Rails 6 adds rails db:prepare to migrate or setup a databaseDecember 10, 2019 · Akhil Gautam