Reputation: 1975
I have an array of objects that I want to count and transform. For instance:
[#<User id:1, count:0>, #<User id:2, count:0>, #<User id:2, count:0>, #<User id:3, count:0>, #<User id:1, count:0>, #<User id:1, count:0>]
would become:
[#<User id:1, count:3>, #<User id:2, count:2>, #<User id:3, count:1>]
The transformation is what confuses me, since a 'map', goes straight through, but this would be recursive.
Upvotes: 0
Views: 90
Reputation: 9225
[user1, user2, user2, user3, user1, user1] \
.group_by(&lambda{|x| x}) \
.map{ |k, v| k.count = v.count; k }
Upvotes: 0
Reputation: 41179
[user1, user2, user2, user3, user1, user1].group_by(&:id).map do |id, users|
users.first.count = users.size
users.first
end
Upvotes: 2