Ruby remove duplicate entries in array of hashes but based on more than one value

Viewed 11165

I've seen numerous questions about this but only with one key, never for multiple keys.

I have the following array of hashes:

a = [{:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"3:21"},
 {:name=>"Chick on the Side", :artist=>"Another Dude", :duration=>"3:20"},
 {:name=>"Luv Is", :duration=>"3:13"},
 {:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"2"},
 {:name=>"Chick on the Side", :artist=>"Another Dude"}]

a.uniq won't work here because the duration is different or might not even exist. I have a unique key set up in the database that does not allow duplicate entries by the same name, artist and composer so I sometimes get errors when people have duplicate entries for these 3 keys.

Is there a way to run uniq that would check for those 3 keys? I tried a block like this:

 new_tracks.uniq do |a_track|
   a_track[:name]
   a_track[:artist]
   a_track[:composer]
 end

But that ignores anything where the key is not present (any entry without a composer does not meet the above criteria for example).

I could always use just the :name key but that would mean I'm getting rid of potentially valid tracks in compilations that have the same title but different artist or composer.

This is with Ruby 2.0.

3 Answers
Related