I have an array of arrays like this:
array = [[1, 'Something', '123456321'], [2, 'Something', '123456321'], [2, 'Something', 1234563212']]
And I want to merge the subarrays that have same id and get this result:
array = [[1, 'Something', '123456321'], [2, 'Something, Something', '123456321, 1234563212']]
Can anyone help me? Thanks!
Best Answer;
array.group_by(&:first).map do |id, records|
names = records.map(&:second).join(', ')
values = records.map(&:last).join(', ')
[id, names, values]
end
As you asked the reversed question recently, I suggest you to read the
Enumerable
, Array
, Hash
and String
documentations. It will give you an instant boost in expressiveness and understanding of how to do common tasks with Ruby.
No comments:
Post a Comment