Sar*_*h W 59 ruby ruby-on-rails ruby-on-rails-3
如果我已经有哈希,我可以这样做
h[:foo]
h['foo']
Run Code Online (Sandbox Code Playgroud)
是相同的?(这被称为无关紧要的访问吗?)
细节:我使用以下内容加载此哈希,initializers但可能不应该有所作为:
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
Run Code Online (Sandbox Code Playgroud)
Aus*_*lor 88
你可以使用with_indifferent_access.
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
Run Code Online (Sandbox Code Playgroud)
mor*_*itz 27
如果你已经有哈希,你可以这样做:
HashWithIndifferentAccess.new({'a' => 12})[:a]
Run Code Online (Sandbox Code Playgroud)
Psy*_*one 17
您也可以这样编写YAML文件:
--- !map:HashWithIndifferentAccess
one: 1
two: 2
Run Code Online (Sandbox Code Playgroud)
之后:
SETTINGS = YAML.load_file("path/to/yaml_file")
SETTINGS[:one] # => 1
SETTINGS['one'] # => 1
Run Code Online (Sandbox Code Playgroud)
使用HashWithIn DifferentAccess代替普通的 Hash。
\n\n为了完整起见,请写:
\n\nSETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"\xc2\xad))\nRun Code Online (Sandbox Code Playgroud)\n
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25707 次 |
| 最近记录: |