Pages

Showing posts with label Hash. Show all posts
Showing posts with label Hash. Show all posts

Sunday, February 11, 2018

Ruby’s Hash Vs ActiveSupport’s HashWithIndifferentAccess


The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :some_value) cannot be retrieved using the equivalent String (e.g. ‘some_value’). 
On the other hand, class HashWithIndifferentAccess is inherited from ruby "Hash" & a special behavior is added in it. HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:

h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"