Rails 6 adds support of symbol keys

Amit Choudhary

Amit Choudhary

August 20, 2019

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.

Rails 5.2

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.

Rails 6.0.0.beta2

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.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.