【发布时间】:2014-04-25 15:06:26
【问题描述】:
我有这个哈希数组:
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}]
我想根据要拥有的键合并它:
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}]
试过了:
ah.inject { |all, h| all.merge(h) } #no success
关于如何做到这一点的任何提示?
更新
是否可以按键/值对的数量对其进行排序?那么具有最多键/值的散列是第一个,而具有最小键值的散列是最后一个?
输出
[{"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}
]
** 更新 2 **
要按键/值对的长度对哈希数组进行排序:
ah.sort {|a, b| a.length <=> b.length}.reverse
【问题讨论】: