From: Robert Klemme Date: 2011-01-18T22:22:09+09:00 Subject: Re: Hash keys exist? On Tue, Jan 18, 2011 at 11: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. 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 -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/