6

I am not able to achieve the desired results with the conventional Ruby methods to remove all duplicate objects from the array, user_list, below. Is there a smart way to solve this problem?

users = []
user_list.each do |u|
    user = User.find_by_id(u.user_id)
    users << user
    #users << user unless users.include?(user)  # does not work
end
#users = users.uniq  # does not work
3
  • 2
    uniq really should work. Could you show the steps you took to test it and what your results were? What is the class of the objects in the user's array and how is their == operator defined? Is this Ruby on Rails? Commented Nov 5, 2013 at 4:25
  • Are you using Rails 4 or Rails 3? Oh right, are you using rails at all? If not, what is the User class from? Commented Nov 5, 2013 at 4:32
  • 2
    Hi guys, this was a false alarm! I have called the method with data in the wrong format. users.uniq is indeed working! Thanks for your help. Commented Nov 5, 2013 at 5:09

4 Answers 4

13

How about this?

users = User.find(user_list.map(&:user_id).uniq)

This has the additional benefit of being one database call instead of user_list.size database calls.

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

1 Comment

This is much more efficient than what he's currently doing. Could also do User.where(user_id: user_list.map(&:user_id)) which will lazily-execute the database query, and handles the uniq automatically.
8
user_list.uniq! 

This should remove all the duplicate value and keep the unique ones in user_list. I hope this is what you are looking for.

Comments

0

You can also use compact to remove nil objects as

MainMenu.first.second_sale_elements.each.map(&:sale_structure).compact.uniq

Comments

0

user_list.uniq! works thanks, but remember uniq! will return a nil object if no duplicates appear, so if you don't have a validator use uniq cuz it will return a new array.

Ruby uniq! documentation

Returns nil if no changes are made (that is, no duplicates are found).

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.