Reputation: 11017
i have some data that looks like this:
[["2000475042", "1"], [{:match_day_uid=>"2000475042", :external_player_uid=>"88", :external_team_uid=>"1", :player_display_name=>"Cardin Constance", :team_display_name=>"Alpha Monkeys", :score=>33}, ...]]
[["2000475042", "2"], [{:match_day_uid=>"2000475042", :external_player_uid=>"253", :external_team_uid=>"2", :player_display_name=>"Cochran Callahan", :team_display_name=>"Ghost Commandos", :score=>169}, ...]]
...
The data is grouped by two ids - match_day_uid
and external_team_uid
in the first array and goes on to list each instance of matching data in the second array.
I want to make a new hash with this data where the grouping is by match_day_uid
with data for each team inside a hash that is keyed by external_team_uid
.
Currently my code looks like this:
def output
output = {}
data_stream.each { |identifiers, data|
output[identifiers[0]] = {
:external_team_uid => identifiers[1],
:team_score => data.map { |p| p[:score] }.inject(:+),
:data => [ data ]
}
}
output
end
and the output is 'right' - i can call output["2000475042"]
and get the data, which looks like this:
{:external_team_uid=>"3", :team_score=>1026, :data=>[ <all the data here> ]}
but there's only one team - which means that the value for the key is being overwritten each time, and i'm left with the data for whatever team was last iterated through.
How can I get the data for ALL the teams as a value for one key (which is the match_day_id)?
Desired Output
:match_days => {
:match_day_1 = [
'3' => {:external_team_uid=>"3", :team_score=>1026, :data=>[ <all the data here> ]},
'4' => {:external_team_uid=>"4", :team_score=>2222, :data=>[ <all the data here> ]},
etc...
],
:match_day_1 = [
'3' => {:external_team_uid=>"3", :team_score=>415, :data=>[ <all the data here> ]},
'4' => {:external_team_uid=>"4", :team_score=>9644, :data=>[ <all the data here> ]},
etc...
]
...
}
Upvotes: 0
Views: 428
Reputation: 9146
def convert(data_stream)
output = {}
data_stream.each { |identifiers, data|
output[identifiers[0]] ||= []
output[identifiers[0]] << {
:external_team_uid => identifiers[1],
:team_score => data.map { |p| p[:score] }.inject(:+),
:data => [ data ]
}
}
output
end
Upvotes: 1