迭代哈希数组并连续输出每次迭代

时间:2014-05-20 07:36:07

标签: ruby loops

我有一个哈希数组,例如:

[{:number=>2131, :owner=>"Mark"},
 {:number=>223, :owner=>"Mark"},
 {:number=>546, :owner=>"Mark"},
 {:number=>765454, :owner=>"Tom"},
 {:number=>845378, :owner=>"Jack"},
 {:number=>75, :owner=>"Jack"},
 {:number=>2342, :owner=>"Jack"}]

如何输出逐行排序的所有者的数字值来获取此信息:

# ["Jack", "Mark", "Tom"]
75 223 765454
2342 546 -
845378 2131 -

每个具有已排序数字的列属于所有者,每行包含来自每个所有者的数字。

1 个答案:

答案 0 :(得分:1)

怎么样?
a = [{:number=>2131, :owner=>"Mark"},
     {:number=>223, :owner=>"Mark"},
     {:number=>546, :owner=>"Mark"},
     {:number=>765454, :owner=>"Tom"},
     {:number=>845378, :owner=>"Jack"},
     {:number=>75, :owner=>"Jack"},
     {:number=>2342, :owner=>"Jack"}]

a1 = a.group_by { |h| h[:owner]  }
#=> {"Mark"=>[{:number=>2131, :owner=>"Mark"}, {:number=>223, :owner=>"Mark"}, {:number=>546, :owner=>"Mark"}], "Tom"=>[{:number=>765454, :owner=>"Tom"}], "Jack"=>[{:number=>845378, :owner=>"Jack"}, {:number=>75, :owner=>"Jack"}, {:number=>2342, :owner=>"Jack"}]}

a2 = a1.map { |k, v| [k, v.sort_by { |v| v[:number] } ] }
#=> [["Mark", [{:number=>223, :owner=>"Mark"}, {:number=>546, :owner=>"Mark"}, {:number=>2131, :owner=>"Mark"}]], ["Tom", [{:number=>765454, :owner=>"Tom"}]], ["Jack", [{:number=>75, :owner=>"Jack"}, {:number=>2342, :owner=>"Jack"}, {:number=>845378, :owner=>"Jack"}]]]

a3 = a2.sort_by { |(v0)| v0 }.to_h
#=> {"Jack"=>[{:number=>75, :owner=>"Jack"}, {:number=>2342, :owner=>"Jack"}, {:number=>845378, :owner=>"Jack"}], "Mark"=>[{:number=>223, :owner=>"Mark"}, {:number=>546, :owner=>"Mark"}, {:number=>2131, :owner=>"Mark"}], "Tom"=>[{:number=>765454, :owner=>"Tom"}]}

max_values_size = a3.values.max_by { |v| v.size }.size
#=> 3

a4 = max_values_size.times.map do |i|
  a3.keys.map do |k|
    a3[k][i] ? a3[k][i][:number] : '-'
  end
end
#=> [[75, 223, 765454], [2342, 546, "-"], [845378, 2131, "-"]]

a4.each { |v| puts v.join(' ') }
#=>
75 223 765454 
2342 546 - 
845378 2131 -

这应该是不言自明的,请问是否不清楚