1

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
1
  • Thanks to everyone for giving me such great answers. Really helps a NOOB learn this stuff. Commented Sep 12, 2011 at 1:56

4 Answers 4

6

Use the uniq method, which returns a new array with duplicates removed.

@managers.uniq
Sign up to request clarification or add additional context in comments.

1 Comment

or @managers.uniq_by {|manager| manager.user_id} (see apidock.com/rails/Array/uniq_by)
1

If by duplicate you mean the same object ID, then you can do the following:

@managers.uniq.group_by(&:name)

Comments

1

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

i agree with you that this looks symptomatic, but does this not lead straight to a N+1 query problem if your 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)
I had a 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.
In my case the way it works is the same person can be the manager of many boards they create. So over time I would get more than one board possibly by the same manager.
1

you can also do

Manager.select('DISTINCT user_id')

to get a clean array in the first place, whith better performance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.