从Ruby中的哈希数组获取数据

时间:2018-12-08 08:43:32

标签: ruby

我从Google工作表中获取了一系列哈希,看起来像这样

itemList = [ {:id => '1', :type => 'A', :category => 'Cat1' }, 
             {:id => '2', :type => 'A', :category => 'Cat1' },
             {:id => '3', :type => 'B', :category => 'Cat1' },
             {:id => '4', :type => 'B', :category => 'Cat1' },
             {:id => '1', :type => 'A', :category => 'Cat2' },
             {:id => '2', :type => 'A', :category => 'Cat2' },
             {:id => '3', :type => 'C', :category => 'Cat2' } ]

我希望能够在终端上打印此

Cat1
A
1, 2
B
3, 4

Cat2
A
1, 2
C
3

有简单的方法吗? 谢谢

1 个答案:

答案 0 :(得分:1)

以下将为您提供所需的格式,

items = itemList.group_by {|x| x[:category] }

val = items.inject({}) do |m,(k,v)|
    tmp = v.group_by { |x| x[:type] }
    m[k] = tmp.update(tmp) { |i,j| j.map { |x| x[:id] } }
    m
end

# => {"Cat1"=>{"A"=>["1", "2"], "B"=>["3", "4"]}, "Cat2"=>{"A"=>["1", "2"], "C"=>["3"]}}

如下所示显示它,

 val.each { |k,v| puts k; v.each { |i,j| puts i; puts j.join(', ') }; puts }

Cat1
A
1, 2
B
3, 4

Cat2
A
1, 2
C
3