Project

General

Profile

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.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:86326]

Description

Abstract

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.

Use-case

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.

Implementation approach

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)
https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary

JavaScript: json-query (npm library)
https://www.npmjs.com/package/json-query

RubyGems: Hashie gem
https://rubygems.org/gems/hashie

Also available in: Atom PDF