Ruby Hashes: Getting Deep

A neat way to test for values deep in the heart of a Hash.

class Hash

  def deep_value(key_array)
    value = self
    Array(key_array).each do |key|
      value = value.fetch(key, nil) 
    end
    value
  rescue NoMethodError
    nil
  end

end

# Examples

h = {1 => {2 => {3 => 4}}}

h.deep_value(1)       #=> {2 => {3 => 4}}
h.deep_value([1,2])   #=> {3 => 4}
h.deep_value([1,2,3,4]) #=> nil

h = {"farm" => {"animals" => ['sheep','pigs']},
     "people" => {"farmers" => ['bill','joe'],
                  "children" => 'tommy'
                  }
    }
    
h.deep_value(["farm","animals"]) #=> ['sheep','pigs']
h.deep_value(["farm","animals","edible"]) #=> nil 
h.deep_value(["farm","people","farmers"]) #=> ['bill','joe']
h.deep_value(["farm","city folk"]) #=> nil

Comments are closed.

About

QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.

twitter/@aq.

instagram/@quirkey.

github/quirkey.

QuirkeyBlog is proudly powered by WordPress

Categories