如果我已经有哈希,我可以这样做吗
h[:foo]
h['foo']
是一样的吗? (这被称为无关紧要的访问吗?)
详细信息:我在initializers
中使用以下内容加载此哈希值,但可能不会产生任何影响:
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
答案 0 :(得分:85)
您可以使用with_indifferent_access
。
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
答案 1 :(得分:25)
如果你已经有哈希,你可以这样做:
HashWithIndifferentAccess.new({'a' => 12})[:a]
答案 2 :(得分:17)
你也可以这样编写YAML文件:
--- !map:HashWithIndifferentAccess
one: 1
two: 2
之后:
SETTINGS = YAML.load_file("path/to/yaml_file")
SETTINGS[:one] # => 1
SETTINGS['one'] # => 1
答案 3 :(得分:3)
使用HashWithIndifferentAccess代替普通哈希。
为完整起见,请写:
SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"))
答案 4 :(得分:1)
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