Rails 6 adds support of symbol keys

Amit Choudhary

By Amit Choudhary

on 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.

1>> info = { name: 'Mark', email: 'mark@bigbinary.com' }.with_indifferent_access
2
3=> {"name"=>"Mark", "email"=>"mark@bigbinary.com"}
4
5>> info.assoc(:name)
6
7=> nil
8
9>> info.assoc('name')
10
11=> ["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.

1>> info = { name: 'Mark', email: 'mark@bigbinary.com' }.with_indifferent_access
2
3=> {"name"=>"Mark", "email"=>"mark@bigbinary.com"}
4
5>> info.assoc(:name)
6
7=> ["name", "Mark"]
8
9>> info.assoc('name')
10
11=> ["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.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.