ruby - iterate over every key in nested hash -
is there simple way iterate on every key in nested hash. have large json , want values of keys, no matter level at. doesn't matter parent is. looking way straight line iterate though each key , return values of keys equal specific string.
module hashnestedget refine hash def nested_get(key) return fetch(key) if has_key?(key) each |subkey, subval| if hash === subval result = subval.nested_get(key) return result if result end end nil end end end = { b: 1, c: { d: { e: 2 } } } using hashnestedget require 'pp' pp a.nested_get(:b) # => 1 pp a.nested_get(:e) # => 2 pp a.nested_get(:d) # => nil
(posted refinement, won't work in irb
; easy enough make plain function if necessary)
Comments
Post a Comment