如果我已经有一个哈希,我可以让这个如果我在Ruby on Rails中有散列,有没有办法让它无差别访问?
h[:foo]
h['foo']
是一样的吗? (这是所谓的冷漠访问?)
的细节:我使用initializers
以下加载该哈希,但可能不应该有所作为:
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
如果我已经有一个哈希,我可以让这个如果我在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
至少在Rails 3.2.8中,这似乎不起作用。我已经使用了这个确切的方法一段时间,并试图在一个新的3.2.8 Rails应用程序中使用它,但尽管ActiveSupport是事实,但似乎没有ActiveSupport :: HashWithIndifferentAccess可以在application.rb中访问。 – slant 2012-09-21 17:45:34
@slant这是因为ActiveSupport已被模块化。如果您希望在应用程序加载过程中尽早提供“active_support/core_ext/hash/indifferent_access”。 – gtd 2013-01-18 16:06:56
@gtd啊,这很有道理。感谢您花时间解释一个。 – slant 2013-01-23 22:36:39
使用HashWithIndifferentAccess,而不是正常的哈希值。
为了完整,写:
SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"))
如果你有一个哈希已,你可以这样做:
HashWithIndifferentAccess.new({'a' => 12})[:a]
所以我认为可能使用'SETTINGS = HashWithIndifferentAccess.new(YAML.load_file(“#{RAILS_ROOT} /config/settings.yml”))'开始? – 2011-05-02 19:37:50
是的,我认为是这样:) – moritz 2011-05-02 20:40:27
你也可以写YAML文件方式:
--- !map:HashWithIndifferentAccess
one: 1
two: 2
后:
SETTINGS = YAML.load_file("path/to/yaml_file")
SETTINGS[:one] # => 1
SETTINGS['one'] # => 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
'RAILS_ROOT'是有利于Rails.root'的'弃用。如果你使用旧的风格,你会得到疯狂的警告。 – tadman 2011-05-02 19:57:54