64

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")
1
  • 2
    RAILS_ROOT is deprecated in favor of Rails.root. You'll get crazy warnings if you use the old style.
    – tadman
    May 2, 2011 at 19:57

5 Answers 5

100

You can just use with_indifferent_access.

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
4
  • This doesn't seem to work anymore in Rails 3.2.8 at least. I have used this exact method for a while, and just tried to use it in a new 3.2.8 Rails app, but it doesn't seem that ActiveSupport::HashWithIndifferentAccess is accessible in application.rb despite the fact that ActiveSupport is.
    – slant
    Sep 21, 2012 at 17:45
  • 3
    @slant That's because ActiveSupport has been modularized. If you want this early in the app load process just require 'active_support/core_ext/hash/indifferent_access' up front.
    – gtd
    Jan 18, 2013 at 16:06
  • @gtd Ah, that makes sense. Thanks for taking the time to explain that one.
    – slant
    Jan 23, 2013 at 22:36
  • 1
    Actually I managed to make it work with require 'active_support/core_ext/hash' Aug 27, 2013 at 1:23
31

If you have a hash already, you can do:

HashWithIndifferentAccess.new({'a' => 12})[:a]
1
  • so I think probably to use SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml")) to begin with?
    – Sarah W
    May 2, 2011 at 19:37
18

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
2
  • will it be ignored by other libraries that would read this file? you might have a settings file to share with a node server for example
    – Frexuz
    Dec 6, 2017 at 11:30
  • Tested with js-yaml and it doesn't work. So !map:HashWithIndifferentAccess is YAML tag and if the library can't understand it probably there will be an error.
    – Psylone
    Dec 8, 2017 at 15:59
6

Use HashWithIndifferentAccess instead of normal Hash.

For completeness, write:

SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"­))
5
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.