Hash with indifferent access

前端 未结 2 785
失恋的感觉
失恋的感觉 2021-02-01 03:14

I have a non-Rails project in which I am loading some settings from a YAML file:

config = YAML::load(File.open(\"#{LOG_ROOT}/config/database.yml\"))
相关标签:
2条回答
  • 2021-02-01 03:48

    Let the config hash return the value for the stringified version of the key:

    config = {"host"=>"value1", "Username"=>"Tom"}
    config.default_proc = proc{|h, k| h.key?(k.to_s) ? h[k.to_s] : nil}
    p config[:host] #=> "value1"
    

    The default_proc runs everytime when a key is not found in the hash. Note this is only half of indifferent access: config["host"] will result in nil if the key :host is present. If that has to work too:

    config.default_proc = proc do |h, k|
       case k
         when String then sym = k.to_sym; h[sym] if h.key?(sym)
         when Symbol then str = k.to_s; h[str] if h.key?(str)
       end
    end
    

    See the comments about limitations of this approach (tltr: separate values for :a and 'a' are possible, does not take into account Hash.delete and others).

    0 讨论(0)
  • 2021-02-01 04:06

    You lose nothing except a few kB of disk space by installing the Active Support gem. In your code, you require only the function you want:

    require 'active_support/core_ext/hash/indifferent_access'
    

    That way, you can be sure you are not getting anything else to mess up your namespace.

    0 讨论(0)
提交回复
热议问题