What is the difference between Ruby's Hash and ActiveSupport's HashWithIndifferentAccess?
What is the difference between Ruby's Hash and 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. :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:
h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"
h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"
Comments
Post a Comment