If I have a hash in Ruby on Rails, is there a way

2020-05-19 03:18发布

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")

5条回答
劳资没心,怎么记你
2楼-- · 2020-05-19 03:57

Use HashWithIndifferentAccess instead of normal Hash.

For completeness, write:

SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"­))
查看更多
戒情不戒烟
3楼-- · 2020-05-19 03:58

You can just use with_indifferent_access.

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
查看更多
够拽才男人
4楼-- · 2020-05-19 04:02
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
查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-19 04:04

If you have a hash already, you can do:

HashWithIndifferentAccess.new({'a' => 12})[:a]
查看更多
不美不萌又怎样
6楼-- · 2020-05-19 04:20

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
查看更多
登录 后发表回答