I have an array of users who are managers.
However there are repeated Users.
I would like to group them so that there is only one instance of each User in the array.
What would be the best 开发者_开发知识库way to go about this?
@managers.sort_by{|obj| obj.id} # Just sorted the data but did not eliminate duplicats
@managers.group_by{|u|u.name} # just created a bunch of arrays for each name
Use the uniq
method, which returns a new array with duplicates removed.
@managers.uniq
If by duplicate you mean the same object ID, then you can do the following:
@managers.uniq.group_by(&:name)
Filtering the array feels like fixing symptoms. Why does the array contain rubbish in the first place?
I would suggest adding a manager?
method to your User
model that returns true if the user is a manager. Then you could to something like
@managers = User.select &:manager?
and get an array that only contains managers.
you can also do
Manager.select('DISTINCT user_id')
to get a clean array in the first place, whith better performance.
精彩评论