ruby-on-rails – 与另一个嵌套哈希相比,从嵌套哈希中查找丢失的
发布时间:2020-12-17 02:06:54 所属栏目:百科 来源:网络整理
导读:我有两个嵌套的哈希值(hash1,hash2),偶然碰巧是从yml文件生成的哈希值.我需要找到hash1中存在但不在hash2中的所有键(完整的父链). 给定这两个哈希值,输出应为hash_diff. hash1 = {"A" = 1,"B" = {"C" = 2,"D" = 3},"E" = 1} hash2 = {"A" = 1,"B" = {"C" = 2
我有两个嵌套的哈希值(hash1,hash2),偶然碰巧是从yml文件生成的哈希值.我需要找到hash1中存在但不在hash2中的所有键(完整的父链).
给定这两个哈希值,输出应为hash_diff. hash1 = {"A" => 1,"B" => {"C" => 2,"D" => 3},"E" => 1} hash2 = {"A" => 1,"B" => {"C" => 2} } hash_diff = {"B" => {"D" => 3},"E" => 1} 请注意,我想要一个类似哈希差异的东西,它只考虑密钥,而不是值. 解决方法
这是解决方案.虽然我修改了原来的hash1
所以用法是: hash_diff(hash1,hash2) hash_diff_var = hash1 def self.hash_diff_helper(hash1,hash2) hash1.each_pair do |k,v| if v.is_a?(Hash) && hash2.key?(k) hash_diff_helper(v,hash2[k]) elsif !v.is_a?(Hash) && hash2.key?(k) hash1.delete(k) end end end def self.hash_diff(hash1,hash2) hash_diff_helper(hash1,hash2) hash1.select!{|k,v| v.present?} end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容