通过只知道值中的一项来获取散列的键,该值是 Ruby 中的数组
Get the key of a hash by knowing only one item inside the value which is an array in Ruby
考虑到我只是 "known_value
的值,我希望能够从中获取名为 "needed key" 的密钥作为字符串
hash = {
"needed key" => {
:key1 => ["know_value", "unknown_value"],
:key2 => ["stuff", "more_stuff"]
}
"otherhash" => {
:key1 => ["unknow_value", "unknown_value"],
:key2 => []
}
}
简而言之,如果我只知道 "know_value",我将如何从这段代码中检索 "needed key"。所以通过简单地使用 "know_value" 我需要得到 "needed key".
非常感谢您的帮助。
希望我说的够清楚,不然请问我再清楚点
hash.select{|k, v| v.values.flatten.include?('known_value')}.keys
不是 Ruby 专家,但我认为这可以完成工作。
hash.keys.select{ |key|
subhash = hash[key]
subhash.keys.any? { |subkey|
subhash[subkey].include? 'known_value'
}
}.first
如果您只关心其中之一,那么您可以使用 find
:
hash.find { |k, h| h.values.flatten.include?('know_value') }.first
或者如果你想避免 flatten
,你可以在内部数组上使用 any?
:
hash.find { |k,h| h.values.any? { |a| a.include?('know_value') } }.first
这是一种提取所需密钥的有效方法,因为它避免了构建临时的中间数组,例如 hash.keys
、flatten
、hash[key]
等等。
target = "known_value"
hash.each_key.find { |k| hash[k].each_value { |a| a.include?(target) } }
#=> "needed key"
当然,这假设我们正在寻找满足要求的任何密钥。
考虑到我只是 "known_value
的值,我希望能够从中获取名为 "needed key" 的密钥作为字符串hash = {
"needed key" => {
:key1 => ["know_value", "unknown_value"],
:key2 => ["stuff", "more_stuff"]
}
"otherhash" => {
:key1 => ["unknow_value", "unknown_value"],
:key2 => []
}
}
简而言之,如果我只知道 "know_value",我将如何从这段代码中检索 "needed key"。所以通过简单地使用 "know_value" 我需要得到 "needed key".
非常感谢您的帮助。
希望我说的够清楚,不然请问我再清楚点
hash.select{|k, v| v.values.flatten.include?('known_value')}.keys
不是 Ruby 专家,但我认为这可以完成工作。
hash.keys.select{ |key|
subhash = hash[key]
subhash.keys.any? { |subkey|
subhash[subkey].include? 'known_value'
}
}.first
如果您只关心其中之一,那么您可以使用 find
:
hash.find { |k, h| h.values.flatten.include?('know_value') }.first
或者如果你想避免 flatten
,你可以在内部数组上使用 any?
:
hash.find { |k,h| h.values.any? { |a| a.include?('know_value') } }.first
这是一种提取所需密钥的有效方法,因为它避免了构建临时的中间数组,例如 hash.keys
、flatten
、hash[key]
等等。
target = "known_value"
hash.each_key.find { |k| hash[k].each_value { |a| a.include?(target) } }
#=> "needed key"
当然,这假设我们正在寻找满足要求的任何密钥。