如果我在Ruby on Rails中有一个哈希值,有没有办法让它无差别的访问?

如果我已经有一个散列,我可以做到这一点

h[:foo] h['foo'] 

是相同的? (这被称为无差别访问?)

细节:我在initializers使用了以下哈希加载,但可能不应该有所作为:

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

你可以使用with_indifferent_access

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

如果你已经有一个散列,你可以这样做:

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

你也可以这样写YAML文件:

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

之后:

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

使用HashWithIndifferentAccess而不是普通的哈希。

为了完整性,写:

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