7

what is the best way to make such deep check:

{:a => 1, :b => {:c => 2, :f => 3, :d => 4}}.include?({:b => {:c => 2, :f => 3}}) #=> true

thanks

OlegZ
  • 175
  • 2
  • 15
  • 4
    It's unclear what you actually wanting this code to do. Do you want to check if the hash has a value that is a hash including key :c with value 2 and key :f with value 3? Are you wanting to check that the hash value for key b: is a hash including key :c with value 2 and key :f with value 3? Or are you wanting to check that the hash value for key b: is _exactly the hash key :c with value 2 and key :f with value 3? Please explain exactly what you want - preferably with some examples that'd return true, and some that'd return false. – SamStephens Sep 30 '10 at 01:30

2 Answers2

5

I think I see what you mean from that one example (somehow). We check to see if each key in the subhash is in the superhash, and then check if the corresponding values of these keys match in some way: if the values are hashes, perform another deep check, otherwise, check if the values are equal:

class Hash
  def deep_include?(sub_hash)
    sub_hash.keys.all? do |key|
      self.has_key?(key) && if sub_hash[key].is_a?(Hash)
        self[key].is_a?(Hash) && self[key].deep_include?(sub_hash[key])
      else
        self[key] == sub_hash[key]
      end
    end
  end
end

You can see how this works because the if statement returns a value: the last statement evaluated (I did not use the ternary conditional operator because that would make this far uglier and harder to read).

Aaa
  • 1,854
  • 12
  • 18
0

I like this one:

class Hash
  def include_hash?(other)
    other.all? do |other_key_value|
      any? { |own_key_value| own_key_value == other_key_value }
    end
  end
end