在哈希中查找数组中的键值

时间:2017-07-10 14:31:25

标签: ruby hash

我有以下哈希类别:

categories = {"horeca" => ["bar", "waiter", "kitchen"], 
              "retail" => ["eerste", "tweede"]}

如果值包含在值数组中,我想找到它们的键。

如下所示

categories.key("bar")

将返回" horeca"

截至目前我只能得到" horeca"如果我做

categories.key(["bar", "waiter", "kitchen"])

4 个答案:

答案 0 :(得分:5)

尝试 Enumberable#find

LongRunning

答案 1 :(得分:5)

正如Máté所提到的,如果你想找到第一个匹配的元素,可以使用find。如果您想要所有匹配的元素,请使用select。要获得你要做的钥匙:

categories.select { |key, values| values.include?("bar") }.map(&:first)

请参阅https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select

答案 2 :(得分:3)

Md. Farhan Memon's solution is generally the preferable solution but it has one downside: If there's no match in the collection, it returns the collection itself – which probably isn't a desirable result. You can fix this with a simple adjustment that combines both detect/find and break:

categories.detect { |key, values| break key if values.include?('bar') }

This breaks and returns the value if it finds it and otherwise returns nil (which I assume to be the preferable behavior).

If your collection may also contain nil values and/or non-arrays, you can improve it further:

categories.detect { |key, values| break key if Array(values).include?('bar') }

The only downside of this general approach is that it's not particularly intuitive to newcomers: You have to know a bit more than just basic Ruby to understand what's going on without running the code first.

答案 3 :(得分:2)

创建中间数组然后先调用它就没有必要了,如果哈希很大并且你想要第一个匹配的值,那么下面的解决方案就更好了

categories.each{ |k,v| break k if v.include?('bar') }
#=> "horeca"