Project

General

Profile

Actions

Feature #5531

closed

deep_value for dealing with nested hashes

Added by weexpectedTHIS (Kyle Peyton) about 13 years ago. Updated about 8 years ago.

Status:
Closed
Target version:
-
[ruby-core:40586]

Description

This feature request stems from dealing with nested hashes, like the params from a request often dealt with in web frameworks.

Conditional code often needs to be written with multiple logical ANDs in order to achieve what this simple function can:

class Hash
def deep_value(*ks)
if ks.size == 1
return self[ks.shift]
else
val = ks.shift
return (self[val].is_a?(Hash) ? self[val].deep_value(*ks) : nil)
end
end

alias dv deep_value
end

deep_value (dv) will simply recurse over a hash given a set of indexes and return the value at the end.

Example:

foo = {:bar => {:baz => 'blah'}}
foo.dv(:bar, :baz)
-> 'blah'
foo.dv(:cats)
-> nil


Related issues 1 (0 open1 closed)

Has duplicate Ruby master - Feature #8246: Hash#traverseClosedmatz (Yukihiro Matsumoto)04/11/2013Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0