Rails ActiveSupport::HashWithIndifferentAccess

HashWithIndifferentAccess inherits from the Hash class and is defined in the ActiveSupport module (one of the key modules used by Rails). HashWithIndifferentAccess objects are instantiated with a normal hash, convert all the keys that are symbols to strings, and allows access to the values with either the string or symbol.

h = HashWithIndifferentAccess.new({:a => "blah"})
puts h # => {"a"=>"blah"}
puts h["a"] # => "blah"
puts h[:a] # => "blah"

Notice that the hash value (“blah”) can be accessed with the hash key as a symbol or a string (h[“a”] and h[:a] both work).

With a regular hash the || operator could be used to achieve a similar effect, but it isn’t as elegant.

hash = {a: "blah"}
puts hash["a"] || hash[:a] # => "blah"

Regular hashes can be converted to instances of the HashWithIndifferentAccess class with the with_indifferent_access method.

hash = {boo: "casper"}
h = hash.with_indifferent_access
p h.class # => ActiveSupport::HashWithIndifferentAccess

The HashWithIndifferentAccess class is a handy tool when working with hashes that may be used outside of a Ruby setting when keys cannot be symbols.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s