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

2019-03-04 14:33发布

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?

标签: arrays ruby hash
3条回答
Ridiculous、
2楼-- · 2019-03-04 15:06
{1 => ["abc"], 2 => ["ccc", "ffffd"]}.select{|_, a| a.length > 1}.keys
# => [2]
查看更多
小情绪 Triste *
3楼-- · 2019-03-04 15:13

One more possible solution :)

{1 => ["abc"], 2 => ["ccc", "ffffd"]}.map { |k, v| k if v.size > 1 }.compact
# => [2]
查看更多
叛逆
4楼-- · 2019-03-04 15:17

Anything like this?

hash.each_key.select { |key| hash[key].count >= 2 }
查看更多
登录 后发表回答