From: rudyseidinger@... Date: 2018-03-28T09:42:52+00:00 Subject: [ruby-core:86361] [Ruby trunk Feature#14636] `Hash` has a method for accessing the shortest path towards a certain key Issue #14636 has been updated by RudySeidinger (Rudy Seidinger). nobu (Nobuyoshi Nakada) wrote: > RudySeidinger (Rudy Seidinger) wrote: > > In this case, is the shortest path towards the first key containing the specified parameter, so would be > > > > ~~~ ruby > > [:a] > > ~~~ > > It is one of the shortest paths, but not only. > > An enumerator may be used here, > > ```ruby > hash.path_to_key(:name) {|path| ...} > ``` > > and > > ```ruby > hash.path_to_key(:name).first > ``` Hmmm, interesting. What would use the block for, in the first scenario? the `yield` of the block would be execute in which context? inside the enumerator? ---------------------------------------- Feature #14636: `Hash` has a method for accessing the shortest path towards a certain key https://bugs.ruby-lang.org/issues/14636#change-71292 * Author: RudySeidinger (Rudy Seidinger) * Status: Open * Priority: Normal * Assignee: * Target version: ---------------------------------------- ## 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 -- https://bugs.ruby-lang.org/ Unsubscribe: