gpt4 book ai didi

Ruby 哈希数组,比较 2 个键并求和另一个键/值

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:29 25 4
gpt4 key购买 nike

在 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'}
]

如果数组有多个散列,其中 :qtynil: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com