我有一個哈希陣列來自一個發電機表,我需要通過一個密鑰進行分組並彙總另一個密鑰的值。我的陣列類似於:紅寶石合併哈希陣列基於密鑰,哈希另一個密鑰的總和值
data = [
{ 'state' => 'Florida', 'minutes_of_sun' => 10, 'timestamp' => 1497531600, 'region' => 'Southeast' },
{ 'state' => 'Florida', 'minutes_of_sun' => 7, 'timestamp' => 1497531600, 'region' => 'Southeast' },
{ 'state' => 'Florida', 'minutes_of_sun' => 2, 'timestamp' => 1497531600, 'region' => 'Southeast' },
{ 'state' => 'Georgia', 'minutes_of_sun' => 15, 'timestamp' => 1497531600, 'region' => 'Southeast' },
{ 'state' => 'Georgia', 'minutes_of_sun' => 5, 'timestamp' => 1497531600, 'region' => 'Southeast' }
]
,我要尋找的最終結果是:
data = [
{ 'state' => 'Florida', 'minutes_of_sun' => 19, 'region' => 'Southeast' },
{ 'state' => 'Georgia', 'minutes_of_sun' => 20, 'region' => 'Southeast' }
]
我已經能夠通過我下面寫了一個方法來做到這一點,但它是緩慢的,笨重。想知道是否有更快/更少的LoC方式來做到這一點?
def combine_data(data)
combined_data = []
data.each do |row|
existing_data = combined_data.find { |key| key['state'] == row['state'] }
if existing_data.present?
existing_data['minutes_of_sun'] += row['minutes_of_sun']
else
combined_data << row
end
end
combined_data
end
'data.group_by {| H | h ['state']} .values.map {| hs | hs.inject {| a,b | a.merge(b){| key,oldval,newval | oldval + newval}}}' – falsetru
'data.group_by {| h | h ['state']} .values.map {| hs | hs.inject {| a,b | a ['minutes_of_sun'] + = b ['minutes_of_sun']; (如果你不介意修改原來的'data'哈希值) – falsetru
[哈希數組中的Sum值如果它們具有相同的值,可能重複](https://stackoverflow.com/questions/43876712/) sum-values-in-hash-array-of-hash-if-they-have-the-the-value)這個問題已經被多次詢問和回答(你是否先嚐試搜索?)只是Google搜索給我帶來了幾十個結果而沒有看太難 – engineersmnky