Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby remove duplicate objects from array

Tags:

ruby

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
like image 888
user2041343 Avatar asked Nov 05 '13 04:11

user2041343


2 Answers

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.

like image 77
CDub Avatar answered Sep 25 '22 02:09

CDub


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.

like image 40
Sonu Oommen Avatar answered Sep 25 '22 02:09

Sonu Oommen