找到值中包含最多元素的键

时间:2015-10-10 15:54:46

标签: ruby hash

我有一个哈希:

new_hash = {
  [1] => [2, 3, 4],
  [2] => [3],
  [3] => [5, 6, 7, 8, 9],
  [4] => [],
}

我想选择具有最多元素的密钥,即第三个密钥。

我尝试了代码,但它给了我一个“没有方法错误”。有人可以就此提出建议吗?

2 个答案:

答案 0 :(得分:3)

试试这个:

hash.max_by{|k,v| v.length}.first
# => returns [3] if your hash is {[1] => [2,3,4], [2] => [3], [3] => [5,6,7,8,9], [4] => []}

使用first方法,因为hash.max_by{|k,v| v.length}返回结构[key, value]的2元素数组。因此我们在其上运行first来获取密钥。如果你想用哈希格式,你可以这样做:

Hash[hash.max_by{|k,v| v.length}]
# => returns { [3] => [5, 6, 7, 8, 9] }

根据您的评论,如果您想使用select

max_value = hash.values.map(&:length).max
hash.select{|k, v| v.length == max_value}
# => returns {[3] => [5, 6, 7, 8, 9]}, but if you had other values with 5 elements, the returned hash will include them too

答案 1 :(得分:-1)

说,

your_hash = { '1': [2, 3, 4], '2': [3], '3': [5, 6, 7, 8, 9], '4': [], '5': [6, 7, 8, 9, 13], '00': [1, 3] }

如果您希望所有对都具有最大值,则可以执行以下操作:

max = your_hash.values.max_by {|a| a.length}.size
your_hash.select { |k, v| v.length == max }
# => {:"3"=>[5, 6, 7, 8, 9], :"5"=>[6, 7, 8, 9, 13]}

获取具有最大长度数组的哈希的键:

   Hash[your_hash.select { |k, v| v.length == max}].keys
   # => [:"3", :"5"]