
Using HashWithIndifferentAccess to access similar looking string and symbolic keys
Have you ever been into a situation where you need to access the element of hash with similar-looking keys? A classic example is a string and symbolic keys looking similar, e.g, :a and “a”. This is very common for modules parsing JSON API response as well as normal HTML request.
HashWithIndifferentAccess is a ruby ActiveSupport class, which can be used to access the different types of the hash keys objects which look similar.
Let’s define two hashes with similar-looking keys
Let’s try to get the value of symbolic hash with its key using the first symbol and then similar looking string key
When you try to get a value using symbolic_hash["a"],
it gives you nil
as a result and that seems to be the wrong output but it is not the case as :a and “a” are the different objects(former is the symbol and later one is a string).
Read Also: Interesting Methods to Work with Ruby Hashes in A Better Way
Similarly, if you want to retrieve the value of string_hash using the symbolic key, you won’t get expected results but symmetrically nothing is wrong.
But Rails provides a solution around it to consider both types of keys as same. HashWithIndifferentAccess is a class which wraps the given hash and does magical things to get us required behavior.
Seems very interesting, right!!!
P.S.: To use HashWithIndifferentAccess class outside Rails application you need to require below core extension.
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
We also specialize in Python, RPA, AI, Django, JavaScript and ReactJS.
Consulting is free – let us help you grow!
