ruby Hash include another hash, deep check
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
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).
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
精彩评论