在 Ruby 中,我有以下哈希数组:
[
{:qty => 1, :unit => 'oz', :type => 'mass'},
{:qty => 5, :unit => 'oz', :type => 'vol'},
{:qty => 4, :unit => 'oz', :type => 'mass'},
{:qty => 1, :unit => 'lbs', :type => 'mass'}
]
我需要做的是通过 :unit
和 :type
比较元素,然后对 :qty
求和他们是一样的。生成的数组应如下所示:
[
{:qty => 5, :unit => 'oz', :type => 'mass'},
{:qty => 5, :unit => 'oz', :type => 'vol'},
{:qty => 1, :unit => 'lbs', :type => 'mass'}
]
如果数组有多个散列,其中 :qty
为 nil
且 :unit
为空 (""
),那么它只会返回其中一个。所以为了扩展上面的例子,这个:
[
{:qty => 1, :unit => 'oz', :type => 'mass'},
{:qty => nil, :unit => '', :type => 'Foo'},
{:qty => 5, :unit => 'oz', :type => 'vol'},
{:qty => 4, :unit => 'oz', :type => 'mass'},
{:qty => 1, :unit => 'lbs', :type => 'mass'},
{:qty => nil, :unit => '', :type => 'Foo'}
]
会变成这样:
[
{:qty => 5, :unit => 'oz', :type => 'mass'},
{:qty => nil, :unit => '', :type => 'Foo'},
{:qty => 5, :unit => 'oz', :type => 'vol'},
{:qty => 1, :unit => 'lbs', :type => 'mass'}
]
编辑:抱歉,在第二个例子中犯了一个错误......它不应该有 o。
最佳答案
从使用 group_by
开始用你想要的 key ,然后 reduce
将每个值中的 qty
放入单个哈希中,或者如果它们都是 nil
,则使用 nil
:
properties.group_by do |property|
property.values_at :type, :unit
end.map do |(type, unit), properties|
quantities = properties.map { |p| p[:qty] }
qty = quantities.all? ? quantities.reduce(:+) : nil
{ type: type, unit: unit, qty: qty }
end
#=> [{:type=>"mass", :unit=>"oz", :qty=>5},
# {:type=>"Foo", :unit=>"", :qty=>nil},
# {:type=>"vol", :unit=>"oz", :qty=>5},
# {:type=>"mass", :unit=>"lbs", :qty=>1}]
properties
是您的第二个示例输入数据。
关于Ruby 哈希数组,比较 2 个键并求和另一个键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421422/