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

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

h[:foo] h['foo'] 

match? (is this called indifferent access?)

Details: I loaded this hash using the following in initializers , but probably shouldn't matter:

 SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml") 
+43
ruby ruby-on-rails ruby-on-rails-3
May 02 '11 at 19:29
source share
5 answers

You can just use with_indifferent_access .

 SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access 
+76
May 2 '11 at 19:42
source share

If you already have a hash, you can do:

 HashWithIndifferentAccess.new({'a' => 12})[:a] 
+22
May 2 '11 at 19:32
source share

You can also write the YAML file this way:

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

after that:

 SETTINGS = YAML.load_file("path/to/yaml_file") SETTINGS[:one] # => 1 SETTINGS['one'] # => 1 
+17
Jan 26 2018-12-21T00:
source share

Use a HashWithIndifferentAccess instead of a regular hash.

For completeness write:

 SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml")) 
+3
May 2 '11 at 19:31
source share
 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 
0
Apr 22 '17 at 14:26
source share



All Articles