简体   繁体   English

如何在哈希内检查数组中的某个值?

[英]How to check for a certain value within an array WITHIN a hash?

I have a hash which holds a series of arrays with values in them: 我有一个哈希,其中包含一系列带有值的数组:

av_hash = {9 => [2,4,6], 10 => [5,7], 11 => [2,3,7]}

how can I check for the presence of a certain number in the array value of a certain hash key? 如何检查某个哈希键的数组值中是否存在某个数字?

So if I wanted for example to find out if key 11 contains the number 2 in its array, what's the best way to go about this? 因此,例如,如果我想确定键11在其数组中是否包含数字2,那么最好的方法是什么?

It's super straightforward. 非常简单。 Get the item with given key using hash[key_name] , then use Enumerable#include? 使用hash[key_name]获取具有给定键的项,然后使用Enumerable#include? to check if the array contains the element you want to find. 检查数组是否包含要查找的元素。

You can either test the specific key you want or iterate over each key/val pair and return the key that includes the number you're looking for: 您可以测试所需的特定密钥,也可以遍历每个密钥/值对,然后返回包含要查找的数字的密钥:

av_hash = {9 => [2,4,6], 10 => [5,7], 11 => [2,3,7]}
search_for = 2

# see if specific key has `search_for` value in it:
av_hash[11].includes? search_for 
# returns true if key 11's array includes 2

# get keys that contain the value:
av_hash.map { |k, v| k if v.include? search_for }.compact
# returns [9, 11]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM