When I found out how the params
could be accessed using both symbol
and string
as keys,
I dived deep to figure out about ActiveSupport::HashWithIndifferentAccess
class in Rails.
In this blog, we will go through it’s implemention. Check the Source Code and Documentation.
> rgb = ActiveSupport::HashWithIndifferentAccess.new
> rgb[:black] = '#000000'
> rgb[:black] # => '#000000'
> rgb['black'] # => '#000000'
So, this is what it is, we can use both symbols and strings as keys to access the Hash.
Then, in what type the keys are actually stored?
> rgb.keys # => ["black"]
Strings! Let’s see how its done.
Write
Above, we have a method which is used to add a key value pair to the hash.
We can see that the key
and value
are being converted before storing.
regular_writer
is just an alias for []=
.
Here are the methods which are used to convert key
and value
.
As we can see, the key is converted to string from symbol and a new object of the same class is created when the value is hash.
Similarly, when we merge!
another hash into this hash, the keys and values are converted before its merged.
Read
When all the keys are strings, how can it be accessed using symbols?
That’s it, the given symbol is converted to string as well!
Finally,
In this post (for beginners),
we saw how ActiveSupport::HashWithIndifferentAccess
class adds magical methods to ruby’s Hash
class.