From: Josh Cheek Date: 2011-01-18T22:23:12+09:00 Subject: Re: Hash keys exist? --00163628369c2ee208049a1ecda7 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jan 18, 2011 at 4:05 AM, Benjamin Fowl wrote: > Is there a way of checking whether a group of keys exist within a hash. > > For example you have the following hash > > example = {:profile => { :name => "John", > :username => > "johnny_bravo"}, > :example1 => { :var1 => "test", > :var2 => "test2" } > } > > now all you want is a function that can be passed an array of required > keys > eg req = [:name, :username, :var1] > > this array can contain any number of required keys is not always just > keys that are in either the profile or example1 sub hashes. > > I've looked at using the .keys method to compare keys but that requires > me to specify where to look in the hash. > > Any help much apreciated > > -- > Posted via http://www.ruby-forum.com/. > > Here is a recursive solution class Hash def nested_keys?(*target_keys) target_keys.all? do |target_key| has_key?(target_key) || values.any? { |value| value.instance_of?(Hash) && value.nested_keys?(target_key) } end end end example = { :profile => { :name => "John", :username => "johnny_bravo" }, :example1 => { :var1 => "test", :var2 => "test2" }, :example2 => { :nested! => { :three_deep => 1 } }, :value_is_nil => nil, } example.nested_keys? :profile # => true example.nested_keys? :profilx # => false example.nested_keys? :profile , :name # => true example.nested_keys? :profile , :namx # => false example.nested_keys? :profile , :name , :var1 # => true example.nested_keys? :profile , :name , :varx # => false example.nested_keys? :value_is_nil # => true example.nested_keys? :three_deep # => true --00163628369c2ee208049a1ecda7--