如果测试哈希有任何一个数字键的 [英] Testing if a hash has any of a number of keys

查看:15
本文介绍了如果测试哈希有任何一个数字键的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来测试散列是否具有数组中的任何键.我想像这样使用它:

I was wondering if there was a better way to test if a hash has any keys from an array. I want to use it something like this:

keys = %w[k1 k2 k5 k6]
none = true if hash.key?(keys)

或者我必须循环这个?

推荐答案

无需循环:

(hash.keys & keys).any? # => true

说明:

.keys 将散列中的所有键作为数组返回.& 与两个数组相交,返回两个数组中存在的任何对象.最后,.any? 检查数组相交是否有任何值.

.keys returns all keys in a hash as an array. & intersects two arrays, returning any objects that exists in both arrays. Finally, .any? checks if the array intersect has any values.

这篇关于如果测试哈希有任何一个数字键的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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