[英]ruby merge array of hashes based on the key and order it by number of key/value pair
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 ** **更新2 **
To sort the array of hashes by lenght of key/value pair: 按键/值对的长度对哈希数组进行排序:
ah.sort {|a, b| a.length <=> b.length}.reverse
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.