views:

241

answers:

1

Arg! Someone replied with an answer, just as I edited the below! So I've put it back to what I had before.

** Original array setup **

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 go about 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.

+3  A: 
>> 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]]}]
Martin DeMello
Thank you Martin - that was spot on.
Les