Hash keys exist?

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

Keep this open as someone might have the answer but I have reworked the
way in which I store my hash.

On Tue, Jan 18, 2011 at 11:05 AM, Benjamin F. [email protected]
wrote:

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.

irb(main):001:0> example = {
irb(main):002:1* :profile => { :name => “John”, :username =>
“johnny_bravo”},
irb(main):003:1* :example1 => { :var1 => “test”, :var2 => “test2” },
irb(main):004:1* }
=> {:profile=>{:name=>“John”, :username=>“johnny_bravo”},
:example1=>{:var1=>“test”, :var2=>“test2”}}

irb(main):005:0> [:name, :username, :var1].all? {|k| example.has_key? k}
=> false
irb(main):006:0> [:profile, :example1].all? {|k| example.has_key? k}
=> true

Cheers

robert

On Tue, Jan 18, 2011 at 4:05 AM, Benjamin F. [email protected]
wrote:

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