Feature #14636

`Hash` has a method for accessing the shortest path towards a certain key

Added by RudySeidinger (Rudy Seidinger) about 2 years ago. Updated about 2 years ago.

Target version:



Hashes, as a collection of key-value pairs, are often used to represent trees. Having a way of traversing the nodes quicker is very valuable when analyzing big hashes.


As pointed here, in the question, and used in gems like, we can infer that such a method would bring value to the core Ruby object, without necessarily needing extensions and taking benefit of the huge performance gain of having a native method

The idea was discussed with Matz at the RubyHackChallenge at Cookpad office in Bristol and expressed here

Implementation approach

I've came with one possible implementation at By using recursive calls, one can continuously store the path until it reaches the desired key, or reset it, in case the last element is not what is been looked for. The advantage of the approach from a iterative one (that was started before) is that, by using recursion, we avoid the overhead of having the store a temporary hash (tree) to fall-back to whenever the end of a sub-hash is reached. The recursive approach is safe due to usage of rb_exec_recursive and the subsequent checking of infinite recursion.

Cases of other languages or libraries

Python: suggested approach at StackOverflow (standard library)

JavaScript: json-query (npm library)

RubyGems: Hashie gem

Also available in: Atom PDF