When I found out how the
params could be accessed using both
string as keys,
I dived deep to figure out about
ActiveSupport::HashWithIndifferentAccess class in Rails.
> 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.
Above, we have a method which is used to add a key value pair to the hash.
We can see that the
value are being converted before storing.
regular_writer is just an alias for
Here are the methods which are used to convert
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.
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!
In this post (for beginners),
we saw how
ActiveSupport::HashWithIndifferentAccess class adds magical methods to ruby’s