The Hash class in Rubys core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :my_value) cannot be retrieved using the equivalent String (e.g. my_value). On the other hand, HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:
rgb = ActiveSupport::HashWithIndifferentAccess.new
rgb[:black] = '#000000'
rgb[:black] # => '#000000'
rgb['black'] # => '#000000'
If we check the object id of rgb[:black] and rgb['black'] it will be same. But for a hash the object id of :my_value and my_value will not be same and thus their value will also not be same.
Another example of hashwithindifferentaccess is the params hash of rails framework.
1 Comment(s)