如果我在Ruby on Rails中有一个哈希值,有没有办法让它无关紧要?

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)

  • @slant那是因为ActiveSupport已经模块化了.如果您希望在应用程序加载过程的早期,只需要预先设置'active_support/core_ext/hash/indifferent_access'. (3认同)

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)


nat*_*vda 6

使用HashWithIn DifferentAccess代替普通的 Hash。

\n\n

为了完整起见,请写:

\n\n
SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"\xc2\xad))\n
Run Code Online (Sandbox Code Playgroud)\n


The*_*pro 5

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)