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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5861532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:04:09  来源:igfitidea点击:

If I have a hash in Ruby on Rails, is there a way to make it indifferent access?

ruby-on-railsrubyruby-on-rails-3

提问by Sarah W

If I already have a hash, can I make it so that

如果我已经有一个散列,我可以这样做吗

h[:foo]
h['foo']

are the same? (is this called indifferent access?)

是相同的?(这叫冷漠访问吗?)

The details: I loaded this hash using the following in initializersbut probably shouldn't make a difference:

详细信息:我使用以下内容加载了这个哈希,initializers但可能不会有什么不同:

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

回答by Austin Taylor

You can just use with_indifferent_access.

你可以只使用with_indifferent_access.

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

回答by moritz

If you have a hash already, you can do:

如果你已经有一个哈希,你可以这样做:

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

回答by Psylone

You can also write the YAML file that way:

您也可以这样编写 YAML 文件:

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

after that:

在那之后:

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

回答by nathanvda

Use HashWithIndifferentAccessinstead of normal Hash.

使用HashWithIndifferentAccess而不是普通的 Hash。

For completeness, write:

为了完整起见,写:

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

回答by TheVinspro

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