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
-
Thanks to everyone for giving me such great answers. Really helps a NOOB learn this stuff.chell– chell2011年09月12日 01:56:30 +00:00Commented Sep 12, 2011 at 1:56
4 Answers 4
Use the uniq method, which returns a new array with duplicates removed.
@managers.uniq
1 Comment
If by duplicate you mean the same object ID, then you can do the following:
@managers.uniq.group_by(&:name)
Comments
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.
3 Comments
manager? method tries to find records associated to each user ? (unless using a "manager" column set to true/false by a callback when applying to a manager job/quiting)role column in mind, with the manager? method returning true if the the user had the matching role. But you are right in your scenario. I guess we don't know enough about the context given here.you can also do
Manager.select('DISTINCT user_id')
to get a clean array in the first place, whith better performance.