红宝石哈希包括另一个哈希,深入检查 [英] ruby Hash include another hash, deep check

查看:149
本文介绍了红宝石哈希包括另一个哈希,深入检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

推荐答案

我想我从这个例子中看出你的意思(以某种方式)。我们检查subhash中的每个键是否在superhash中,然后检查这些键的相应值是否以某种方式匹配:如果值为散列值,则执行另一个深度检查,否则检查值是否相等:

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

你可以看到这是如何工作的,因为 if 语句返回一个值:最后一个语句被评估(我没有使用三元条件运算符,因为这会使得这个更加丑陋而且难以阅读)。

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

这篇关于红宝石哈希包括另一个哈希,深入检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆