在Ruby中,我有以下哈希值的數組:紅寶石陣列,比較2個鍵和總結其他鍵/值
[
{: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'}
]
編輯:對不起,在第二個例子中犯了一個錯誤......它不應該有鄰。
你打算怎麼給加分? – sawa
你的第二個例子沒有意義,爲什麼在結果中沒有單位「o」的散列? –
你說得對,只是編輯它。 –