陣列具有:Ruby on Rails的 - 獲取在陣列中的多個按鍵max和總和組在同一時間
[ { 'a' => 1, 'b' => 1, 'c' => 1, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 1, 'c' => 2, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 1, 'c' => 3, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 2, 'c' => 4, 'd' => 2, 'e' => 2 },
{ 'a' => 1, 'b' => 2, 'c' => 5, 'd' => 2, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 6, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 7, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 8, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 2, 'c' => 9, 'd' => 4, 'e' => 2 },
{ 'a' => 2, 'b' => 2, 'c' => 10, 'd' => 4, 'e' => 2 } ]
我想分組「C」,和「d」,和「E」的最大值由'a'和'b'組成。
所以,結果應該是:
[ { 'a' => 1, 'b' => 1, 'c' => 3, 'd' => 3, 'e' => 6},
{ 'a' => 1, 'b' => 2, 'c' => 5, 'd' => 4, 'e' => 4},
{ 'a' => 2, 'b' => 1, 'c' => 8, 'd' => 9, 'e' => 6},
{ 'a' => 2, 'b' => 2, 'c' => 10, 'd' => 8, 'e' => 4} ]
到目前爲止,我跟着How to find max value grouped by multiple keys in array of hashes?,使用此代碼來獲得各組
a.group_by { |h| h.values_at("a", "b") }.map { |_, v| v.max_by { |h| h["c"] } }
的最大請指引我,讓總和了。非常感謝。
P/S:使用Ruby 1.8.7和Rails 2.3.5
如果我的問題重複,那麼可以給我一樣的嗎?謝謝 – Anh 2015-02-12 02:50:52