Ruby 使用group_by从数组创建哈希

Ruby 使用group_by从数组创建哈希,ruby,group-by,ruby-hash,Ruby,Group By,Ruby Hash,我有以下数组 ages = [["a", 15],["b", 16], ["c", 15], ["d", 16], ["e", 17], ["f", 20]] 我必须创建一个以年龄为值的散列,它看起来像这样 {15 => ["a","c"], 16=> ["b","d]....} 当我通过方法

我有以下数组

ages = [["a", 15],["b", 16], ["c", 15], ["d", 16], ["e", 17], ["f", 20]]
我必须创建一个以年龄为值的散列,它看起来像这样

{15 => ["a","c"], 16=> ["b","d]....}
当我通过方法运行组_时:

puts ages.group_by {|list| list[1]}
这就是我得到的:

{15=>[["a", 15], ["c", 15]], 16=>[["b", 16], ["d", 16]], 17=>[["e", 17]], 20=>[["f", 20]]}
如果您能澄清如何使这个更干净,并将值作为具有相同年龄的名称数组,我将不胜感激

ages = [["a", 15],["b", 16], ["c", 15], ["d", 16], ["e", 17], ["f", 20]]
您可以简化第一步:

ages.group_by(&:last)
  #=> {15=>[["a", 15], ["c", 15]],
  #    16=>[["b", 16], ["d", 16]],
  #    17=>[["e", 17]],
  #    20=>[["f", 20]]}
然后只需将值转换为所需的数组:

ages.group_by(&:last).transform_values { |arr| arr.map(&:first) }
  #=> {15=>["a", "c"],
  #    16=>["b", "d"],
  #    17=>["e"],
  #    20=>["f"]}
什么时候

比如说,

arr.map(&:first)
  #=> ["a", "c"] 

您可以简化第一步:

ages.group_by(&:last)
  #=> {15=>[["a", 15], ["c", 15]],
  #    16=>[["b", 16], ["d", 16]],
  #    17=>[["e", 17]],
  #    20=>[["f", 20]]}
然后只需将值转换为所需的数组:

ages.group_by(&:last).transform_values { |arr| arr.map(&:first) }
  #=> {15=>["a", "c"],
  #    16=>["b", "d"],
  #    17=>["e"],
  #    20=>["f"]}
什么时候

比如说,

arr.map(&:first)
  #=> ["a", "c"] 

看。

谢谢你,卡里!非常有用。真的很感激!谢谢你,卡里!非常有用。真的很感激!