Pages

Thursday, May 1, 2014

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

Suppose you have the following array of hashes:

new_tracks = [{: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"}]

uniq accepts a block. If a block is given, it will use the return value of the block for comparison.
You can join the attributes you want into a string and return that string.

new_tracks.uniq { |track| [track[:name], track[:artist]].join(":") }

The resultant of above code will be an array of hashes unique on the basis of name and artist attributes.

1 comment:

  1. It was very nice article and it is very useful to Testing tools learners.We also provide Ruby on Rails Online Training

    ReplyDelete