Access Ruby Hash Using Dotted Path Key String

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

    Yeah, I don't think that's built-in, anywhere else. But I use something like this in one of my projects:

    class Hash
      def dig(dotted_path)
        parts = dotted_path.split '.', 2
        match = self[parts[0]]
        if !parts[1] or match.nil?
          return match
        else
          return match.dig(parts[1])
        end
      end
    end
    

    And then call it like

    my_hash = {'a' => {'b' => 'a-b', 'c' => 'a-c', 'd' => {'e' => 'a-d-e'}}, 'f' => 'f'}
    my_hash.dig('a.d.e') # outputs 'a-d-e' (by calling my_hash['a']['d']['e'])
    

提交回复
热议问题