Skip to content

Instantly share code, notes, and snippets.

@dinglixiang
Last active August 29, 2015 14:28
Show Gist options
  • Save dinglixiang/94b4639d21fdbf771756 to your computer and use it in GitHub Desktop.
Save dinglixiang/94b4639d21fdbf771756 to your computer and use it in GitHub Desktop.
Hash[Convert dotted path to key strings]
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

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'])

Ref: http://stackoverflow.com/a/7139631

#####Another implementation with array

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

Ref: http://stackoverflow.com/a/31947281

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment