If I have a hash in Ruby on Rails, is there a way to make it indifferent access?

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


If I already have a hash, can I make it so that

h[:foo]
h['foo']

are the same? (is this called indifferent access?)

The details: I loaded this hash using the following in initializers but probably shouldn't make a difference:

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can just use with_indifferent_access.

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access

Solution 2 - Ruby on-Rails

If you have a hash already, you can do:

HashWithIndifferentAccess.new({'a' => 12})[:a]

Solution 3 - Ruby on-Rails

You can also write the YAML file that way:

--- !map:HashWithIndifferentAccess
one: 1
two: 2

after that:

SETTINGS = YAML.load_file("path/to/yaml_file")
SETTINGS[:one] # => 1
SETTINGS['one'] # => 1

Solution 4 - Ruby on-Rails

Use HashWithIndifferentAccess instead of normal Hash.

For completeness, write:

SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"­))

Solution 5 - Ruby on-Rails

You can just make a new hash of HashWithIndifferentAccess type from your hash.

hash = { "one" => 1, "two" => 2, "three" => 3 }
=> {"one"=>1, "two"=>2, "three"=>3}

hash[:one]
=> nil 
hash['one']
=> 1 


make Hash obj to obj of HashWithIndifferentAccess Class.

hash =  HashWithIndifferentAccess.new(hash)
hash[:one]
 => 1 
hash['one']
 => 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSarah WView Question on Stackoverflow
Solution 1 - Ruby on-RailsAustin TaylorView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmoritzView Answer on Stackoverflow
Solution 3 - Ruby on-RailsPsyloneView Answer on Stackoverflow
Solution 4 - Ruby on-RailsnathanvdaView Answer on Stackoverflow
Solution 5 - Ruby on-RailsTheVinsproView Answer on Stackoverflow