Access Ruby Hash Using Dotted Path Key String

后端 未结 7 2258
情深已故
情深已故 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:07

    This code not only allows dot notation to traverse a Hash but also square brackets to traverse Arrays with indices. It also avoids recursion for efficiency.

    class Hash
    
      def key_path(dotted_path)
        result = self
        dotted_path.split('.').each do |dot_part|
          dot_part.split('[').each do |part|
            if part.include?(']')
              index = part.to_i
              result = result[index] rescue nil
            else
              result = result[part] rescue nil
            end
          end
        end
    
        result
      end
    
    end
    

    Example:

    a = {"b" => {"c" => [0, [1, 42]]}}
    a.key_path("b.c[-1][1]") # => 42
    

提交回复
热议问题