How do I find keys in my hash to map to elements t

2019-03-04 15:13发布

问题:

I have a hash that maps integers to arrays. For example

{1 => ["abc"], 2 => ["ccc", "ddd"]}

How do I get all the keys from my hash that have arrays with at least 2 elements in them?

回答1:

{1 => ["abc"], 2 => ["ccc", "ddd"]}.select{|_, a| a.length > 1}.keys
# => [2]


回答2:

Anything like this?

hash.each_key.select { |key| hash[key].count >= 2 }


回答3:

One more possible solution :)

{1 => ["abc"], 2 => ["ccc", "ddd"]}.map { |k, v| k if v.size > 1 }.compact
# => [2]


标签: arrays ruby hash