检查两个散列是否具有相同的密钥集 [英] Check if two hashes have the same set of keys

查看:74
本文介绍了检查两个散列是否具有相同的密钥集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查两个散列h1h2是否具有相同的密钥组而不考虑顺序的最有效方法是什么?能否使它比我发布的答案更快或更简洁,效率更高?

What is the most efficient way to check if two hashes h1 and h2 have the same set of keys disregarding the order? Could it be made faster or more concise with close efficiency than the answer that I post?

推荐答案

尝试:

# Check that both hash have the same number of entries first before anything
if h1.size == h2.size
    # breaks from iteration and returns 'false' as soon as there is a mismatched key
    # otherwise returns true
    h1.keys.all?{ |key| !!h2[key] }
end

可枚举#all?

最糟糕的情况是,您只需要遍历键一次.

worse case scenario, you'd only be iterating through the keys once.

这篇关于检查两个散列是否具有相同的密钥集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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