Si j’ai déjà un hash, puis-je le faire pour que
h[:foo] h['foo']
sont identiques? (Est-ce que cela s’appelle un access indifférent?)
Les détails: J’ai chargé ce hachage en utilisant les éléments suivants dans les initializers
mais ne devrait probablement pas faire la différence:
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
Vous pouvez simplement utiliser with_indifferent_access
.
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
Si vous avez déjà un hash, vous pouvez faire:
HashWithIndifferentAccess.new({'a' => 12})[:a]
Vous pouvez également écrire le fichier YAML comme suit:
--- !map:HashWithIndifferentAccess one: 1 two: 2
après ça:
SETTINGS = YAML.load_file("path/to/yaml_file") SETTINGS[:one] # => 1 SETTINGS['one'] # => 1
Utilisez HashWithIndifferentAccess au lieu du Hash normal.
Pour être complet, écrivez:
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