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]]}]
精彩评论