简体   繁体   中英

Ruby, unique hashes in array based on multiple fields

I'd like to get back an array of hashes based on sport and type combination

I've got 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'd like to get back:

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

I tried to use (pseudocode):

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

I know I can create such array with loops, I'm quite new to ruby and I'm curious if there's a better (more elegant) way to do it.

尝试使用阵列#values_at以产生阵列uniq通过。

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

One solution is to build some sort of key with the sport and type, like so:

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

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

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM