Make Ruby hashes with String keys also accessible by :symbols

If you want to access the keys as symbols of your hashes which have keys made of strings or mixed key types, then you should use the ActiveSupport HashWithIndifferentAccess hash type.

It's usable in Rails by default, but also in non-Rails project you can use it, too.

Standalone install:

gem install activesupport

Usage:

require 'active_support/hash_with_indifferent_access'
my_hash = { 'key' => 'value', 'more' => 'stuff' }
my_hash = HashWithIndifferentAccess.new my_hash
my_hash[:key] # => 'value'

It also works with nested hash structures!

But it only works for String/Symbol keys. Numbers are still numbers -- who wanna symbolize numbers?

Maybe someone always want to use the extended Hash type, so try:

require 'active_support/hash_with_indifferent_access'
Hash = HashWithIndifferentAccess
# (irb):xx: warning: already initialized constant Hash

This warning is because Hash is already defined.

You also could use another shorter name like HashWIA or something else (to avoid these warnings).

Deutsch

Kurze Beschreibung: Ich zeige hier, wie du deine Hashes immer mit Symbol-Schlüsseln ansprechen kannst, die z. B. aus String-Schlüsseln bestehen, oder gemixt sind (Zeichenketten und Symbole).

Der Trick besteht darin, aus der ActiveSupport-Gem den "HashWithIndifferentAccess"-Typ zu benutzen. Dies ermöglicht dir immer, auch die String-Schlüssel als Symbole zu schreiben. Viel Spaß damit!