Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby Hash include another hash, deep check

Tags:

include

ruby

hash

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

like image 550
OlegZ Avatar asked Sep 30 '10 00:09

OlegZ


1 Answers

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).

like image 153
Aaa Avatar answered Sep 24 '22 16:09

Aaa