[英]Is it possible to pattern match on a hash value to get the hash key in Ruby 3?
這是Ruby 3中關於模式匹配的一道題。
我有一個 hash:
h = {
x: [1, 2, 3],
y: [11, 12, 13],
z: [100, 101],
}
給定 integer(例如13
),我想找到 hash 鍵,其 hash 值包含 integer(示例中的:y
)。
當然,在 Ruby 中有一些方法可以不使用模式匹配來做到這一點。
在這里,我只對在 hash上使用 Ruby 3 的模式匹配來實現這一點感興趣。 通常,Ruby 中的模式匹配匹配 hash 的鍵,而不是值。 另外,這個 hash 有很多鍵,我們事先不知道鍵名。
我發現的最接近的方法是先將 hash 轉換為數組,然后在數組上使用模式匹配。
def find_the_key(a_hash, a_number)
case a_hash.to_a
in [*, [the_key, [*, ^a_number, *]], *]
the_key
else
:key_not_found
end
end
puts find_the_key(h, 13) => :y
puts find_the_key(h, 999) => :key_not_found
有沒有辦法通過在 hash 本身上使用模式匹配來完成這項工作,即,無需先轉換為數組?
還有其他應用模式匹配的方法來解決這個問題嗎?
謝謝
這是我能想到的最接近的東西。 首先將您的模式匹配限制為a_hash.values
(這實際上是您唯一要匹配的東西),使用=>the_value
將匹配的所需部分分配給變量,然后使用a_hash.key(the_value)
:
h = {
x: [1, 2, 3],
y: [11, 12, 13],
z: [100, 101],
}
def find_the_key(a_hash, a_number)
case a_hash.values
in [*, [*, ^a_number, *]=>the_value, *]
the_key = a_hash.key(the_value)
else
:key_not_found
end
end
puts find_the_key(h, 13) #=> y
puts find_the_key(h, 77) #=> key_not_found
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.