Ruby, unique hashes in array based on multiple fields

来源:互联网 发布:业余足球平台软件 编辑:程序博客网 时间:2024/06/14 01:38

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.

Try using Array#values_at to generate an array to uniq by.

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

0 0
原创粉丝点击