Ruby, unique hashes in an array based on several fields

I would like to return an hash array based on a combination of sport and type

I have the following array:

[ { sport: "football", type: 11, other_key: 5 }, { sport: "football", type: 12, othey_key: 100 }, { sport: "football", type: 11, othey_key: 700 }, { sport: "basketball", type: 11, othey_key: 200 }, { sport: "basketball", type: 11, othey_key: 500 } ] 

I would like to return:

 [ { sport: "football", type: 11, other_key: 5 }, { sport: "football", type: 12, othey_key: 100 }, { sport: "basketball", type: 11, othey_key: 200 }, ] 

I tried using (pseudo code):

 [{}, {}, {}].uniq { |m| m.sport and m.type } 

I know that I can create such an array with loops, I'm completely new to rubies, and I'm curious if there is a better (more elegant) way to do this.

+6
source share
3 answers

Try using Array # values_at to generate an uniq array.

 sports.uniq{ |s| s.values_at(:sport, :type) } 
+13
source

One solution is to create a kind of key with a sport and type, for example:

 arr.uniq{ |m| "#{m[:sport]}-#{m[:type]}" } 

The uniq way is that it uses the return value of the block to compare elements.

+5
source
 require 'pp' data = [ { sport: "football", type: 11, other_key: 5 }, { sport: "football", type: 12, othey_key: 100 }, { sport: "football", type: 11, othey_key: 700 }, { sport: "basketball", type: 11, othey_key: 200 }, { sport: "basketball", type: 11, othey_key: 500 } ] results = data.uniq do |hash| [hash[:sport], hash[:type]] end pp results --output:-- [{:sport=>"football", :type=>11, :other_key=>5}, {:sport=>"football", :type=>12, :othey_key=>100}, {:sport=>"basketball", :type=>11, :othey_key=>200}] 
+4
source

Source: https://habr.com/ru/post/975500/


All Articles