ruby Hash include another hash, deep check

2019-04-08 06:04发布

问题:

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

回答1:

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



回答2:

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