[英]How do I get the key for a certain value in a nested hash in ruby?
This is a follow question to another topic I posted earlier.这是我之前发布的另一个主题的后续问题。
Say I have the following hash.假设我有以下哈希。
my_hash = {
'array1' => %w[
value1
value2
],
'array2' => %w[
value3
value4
]
}
What is the fastest or simplest way to get the key for a certain value in one of the arrays.在其中一个数组中获取某个值的键的最快或最简单的方法是什么。 For example, I want to get the key for value2, and get array1, or get the key for value3 and get array2
比如我想获取value2的key,获取array1,或者获取value3的key,获取array2
The fastest you can go with the existing data structure is to scan all arrays in the Hash:使用现有数据结构最快的方法是扫描哈希中的所有数组:
key, _ = my_hash.find{|k, v| v.include? "value3" }
If this lookup is an operation that is performed many times and you need to go faster than this, you may consider a data structure that allows for faster lookups, like one of the following:如果此查找是一个执行多次的操作,并且您需要比这更快,您可以考虑允许更快查找的数据结构,例如以下之一:
my_hash.detect { |_, v| v.include? 'value2' }.first
Please note, that if there are many keys, having value2
in the values array, this approach will return the very first one.请注意,如果有很多键,在 values 数组中有
value2
,这种方法将返回第一个。
To receive all keys, one might use:要接收所有密钥,可以使用:
my_hash.select { |_, v| v.include? 'value2' }.to_h.keys
or:或者:
my_hash.map { |k, v| k if v.include?('value2') }.compact
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.