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

前端 未结 5 1746
-上瘾入骨i
-上瘾入骨i 2021-02-01 12:04

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

相关标签:
5条回答
  • 2021-02-01 12:48

    Use HashWithIndifferentAccess instead of normal Hash.

    For completeness, write:

    SETTINGS = HashWithIndifferentAccess.new(YAML.load_file("#{RAILS_ROOT}/config/settings.yml"­))
    
    0 讨论(0)
  • 2021-02-01 12:49

    If you have a hash already, you can do:

    HashWithIndifferentAccess.new({'a' => 12})[:a]
    
    0 讨论(0)
  • 2021-02-01 12:51

    You can also write the YAML file that way:

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

    after that:

    SETTINGS = YAML.load_file("path/to/yaml_file")
    SETTINGS[:one] # => 1
    SETTINGS['one'] # => 1
    
    0 讨论(0)
  • 2021-02-01 12:58

    You can just use with_indifferent_access.

    SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
    
    0 讨论(0)
  • 2021-02-01 13:07
    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
    
    0 讨论(0)
提交回复
热议问题