简体   繁体   中英

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

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 to 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]]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM