From: "Ondřej Bílka" Date: 2011-11-07T00:59:41+09:00 Subject: [ruby-core:40784] Re: [ruby-trunk - Feature #5531] deep_value for dealing with nested hashes Do you need hash or something like multidimensional hash class that uses [], each iterates on nested... On Sun, Nov 06, 2011 at 05:48:52PM +0900, Thomas Sawyer wrote: > > Issue #5531 has been updated by Thomas Sawyer. > > > Probably best to use #[] internally too. > > class Hash > def [](*keys) > keys.inject(self) {|container, key| value = container[key]; value ? value : return value} > end > end > > @Alexey you may have a point. But I suspect it would need to be conditioned off of responding to #to_h or #to_hash instead of using `is_a?(Hash)`. > > ---------------------------------------- > Feature #5531: deep_value for dealing with nested hashes > http://redmine.ruby-lang.org/issues/5531 > > Author: Kyle Peyton > Status: Open > Priority: Normal > Assignee: > Category: > Target version: > > > 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 > > > > -- > http://redmine.ruby-lang.org -- network packets travelling uphill (use a carrier pigeon)