Removing “duplicate objects” with same attributes using Array.map

Posted by keruilin on Stack Overflow See other posts from Stack Overflow or by keruilin
Published on 2010-05-08T00:03:24Z Indexed on 2010/05/08 0:08 UTC
Read the original article Hit count: 139

As you can see in the current code below, I am finding the duplicate based on the attribute recordable_id. What I need to do is find the duplicate based on four matching attributes: user_id, recordable_type, hero_type, recordable_id. How must I modify the code?

heroes = User.heroes

for hero in heroes
  hero_statuses = hero.hero_statuses

  seen = []

  hero_statuses.sort! {|a,b| a.created_at <=> b.created_at } # sort by created_at
  hero_statuses.each do |hero_status|
    if seen.map(&:recordable_id).include? hero_status.recordable_id # check if the id has been seen already
      hero_status.revoke
    else
      seen << hero_status # if not, add it to the seen array
    end
  end
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby