Access Ruby Hash Using Dotted Path Key String

后端 未结 7 2167
情深已故
情深已故 2021-01-01 21:35

The Rails I18n library transforms a YAML file into a data structure that is accessible via a dotted path call using the t() function.

t(\'one.two.three.four\         


        
相关标签:
7条回答
  • 2021-01-01 22:22

    Just split on a dot in the path and iterate over this to find the right hash?

    path.split(".").inject(hash) { |hash, key| hash[key] }
    

    Alternatively you can build a new hash by iterating recursively over the whole structure:

    def convert_hash(hash, path = "")
      hash.each_with_object({}) do |(k, v), ret|
        key = path + k
    
        if v.is_a? Hash
          ret.merge! convert_hash(v, key + ".")
        else
          ret[key] = v
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题