[英]how can iterate over an array of array of hashes in ruby
我有一個列表如下:
order = [
{term: 201, x: 2},
{term: 201, y: 7},
{term: 201, z: 2},
{term: 202, a: 3},
{term: 202, b: 4},
{term: 202, c: 0}
]
我怎樣才能得到這個結果?
[
{term: 201, x: 2, y: 7, z: 2},
{term: 202, a: 3, b: 4, c: 0},
]
您可以使用group_by
方法:
order.group_by { |h| h[:term] }
.map { |_, v| v.inject(:update) }
# => [{:term=>201, :x=>2, :y=>7, :z=>2}, {:term=>202, :a=>3, :b=>4, :c=>0}]
按術語編號對小哈希進行分組。
然后迭代每組小哈希。
在迭代時合並所有小散列以形成一個散列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.