`Hash` has a method for accessing the shortest path towards a certain key
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 https://stackoverflow.com/questions/8301566/find-key-value-pairs-deep-inside-a-hash-containing-an-arbitrary-number-of-nested, and used in gems like https://rubygems.org/gems/hashie, 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 https://github.com/ko1/rubyhackchallenge/issues/44.
I've came with one possible implementation at https://github.com/ruby/ruby/pull/1847. 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)
RubyGems: Hashie gem