开发者

How to merge the contents of arrays of hashes (keys and contents) in Ruby

开发者 https://www.devze.com 2022-12-10 19:44 出处:网络
myArray = [{\"papers\"=>[[1,2,3],[1,3,2]], \"value\"=>\"1\"}, {\"papers\"=>[[2,1,3],[2,3,1]], \"value\"=>\"1\"},
myArray = [{"papers"=>[[1,2,3],[1,3,2]], "value"=>"1"},
           {"papers"=>[[2,1,3],[2,3,1]], "value"=>"1"}, 
           {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

I need 开发者_StackOverflowto merge the contents based on the "value" of each contained array, so that I end up with something like this:

myArray = [{"papers"=>[[1,2,3],[1,3,2],[2,1,3],[2,3,1]], "value"=>"1"}, 
           {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

How would I do this in the Ruby way?

I thought about iterating over the array, and creating a new array based on the values, but I keep tying myself in knots trying to work out how to define what gets copied.


>> myArray = [{"papers"=>[[1,2,3],[1,3,2]], "value"=>"1"},
?>            {"papers"=>[[2,1,3],[2,3,1]], "value"=>"1"}, 
?>            {"papers"=>[[1,2,3],[1,3,2]], "value"=>"0.5"}]

>> hash = Hash.new {|h,k| h[k] = []}

>> myArray.each {|entry| hash[entry['value']] += entry['papers']}

>> hash
=> {"1"=>[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]], "0.5"=>[[1, 2, 3], [1, 3, 2]]}

>> hash.map {|k,v| {"value" => k, "papers" => v}}
=> [{"value"=>"1", "papers"=>[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]]}, {"value"=>"0.5", "papers"=>[[1, 2, 3], [1, 3, 2]]}]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号