Reputation: 2153
I have this array of hashes:
ah = [{"Date"=>"2014-03-17", "countdown 7"=>1}, {"Date"=>"2014-03-17", "voice 6"=>1},
{"Date"=>"2014-03-18", "voice 1"=>1}, {"Date"=>"2014-03-18", "voice 2"=>0},
{"Date"=>"2014-03-18", "voice 3"=>1}, {"Date"=>"2014-03-18", "voice 4"=>0},
{"Date"=>"2014-03-18", "voice 5"=>0}, {"Date"=>"2014-03-18", "voice 6"=>0},
{"Date"=>"2014-03-19", "voice 5"=>0}, {"Date"=>"2014-03-19", "voice 6"=>0},
{"Date"=>"2014-03-20", "countdown 5"=>1}, {"Date"=>"2014-03-20", "voice 7"=>0},
{"Date"=>"2014-03-20", "voice 6"=>0}]
and i want to merge it based on the key to have :
ah = [{"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},
{"Date"=>"2014-03-18", "voice 1"=>1, "voice 2"=>0, "voice 3"=>1, "voice 4"=>0, "voice 5"=>0, "voice 6"=>0},
{"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0},
{"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0}]
Tried :
ah.inject { |all, h| all.merge(h) } #no success
Any hints on how to do that?
update
Would it be possible to sort it by number of key/value pair? So that the hash that have the most key/value be the first and the one that has the least key value be last?
Output
[{"Date"=>"2014-03-18", "voice 1"=>1, "voice 2"=>0, "voice 3"=>1, "voice 4"=>0, "voice 5"=>0, "voice 6"=>0},
{"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0},
{"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},
{"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0}
]
** Update 2 **
To sort the array of hashes by lenght of key/value pair:
ah.sort {|a, b| a.length <=> b.length}.reverse
Upvotes: 0
Views: 595
Reputation: 118271
I'd do :
ah.group_by { |h| h['Date'] }.map { |_,v| v.inject(:update) }
# => [{"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},
# {"Date"=>"2014-03-18",
# "voice 1"=>1,
# "voice 2"=>0,
# "voice 3"=>1,
# "voice 4"=>0,
# "voice 5"=>0,
# "voice 6"=>0},
# {"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0},
# {"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0}]
Upvotes: 5