Feature #8246

Hash#traverse

Added by Zachary Scott about 1 year ago. Updated about 1 year ago.

[ruby-core:54160]
Status:Open
Priority:Low
Assignee:Yukihiro Matsumoto
Category:core
Target version:-

Description

=begin
From (())

Traverses the given levels of a hash and returns the value associated with the
last key provided. Allows for concise access for deeply nested hashes - often encountered with dealing with external restful apis.

(({hash = { level1: { level2: { level3: 3 } } }}))
(({hash.traverse :level1, :level2, :level3 #=> 3}))
Also supports a default value block if the value is nil or the key is
not found.

(({hash.traverse(:level1, :level2, :nonexistentkey) { 5 } #=> 5}))
=end

275.patch Magnifier (3.05 KB) Zachary Scott, 04/11/2013 08:03 AM


Related issues

Related to ruby-trunk - Feature #8237: Logical method chaining via inferred receiver Open 04/08/2013
Duplicates ruby-trunk - Feature #5531: deep_value for dealing with nested hashes Assigned 11/01/2011

History

#1 Updated by Marc-Andre Lafortune about 1 year ago

  • Assignee set to Yukihiro Matsumoto
  • Priority changed from Normal to Low

Marking as duplicate of #5531.
It's also related to #8237 because one could envision something like:

hash[:level1]??.[:level2]??.[:non_existent_key] || 5

#2 Updated by Charles Nutter about 1 year ago

As a feature that affects all Ruby implementations, this should probably move to CommonRuby: https://bugs.ruby-lang.org/projects/common-ruby

Also available in: Atom PDF