Ruby,基于多个字段的数组中的唯一哈希

时间:2014-09-18 18:47:53

标签: ruby arrays

我想根据运动和类型组合取回一系列哈希

我有以下数组:

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

我想回来:

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

我尝试使用(伪代码):

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

我知道我可以使用循环创建这样的数组,我对ruby很新,我很好奇是否有更好(更优雅)的方法。

3 个答案:

答案 0 :(得分:16)

尝试使用Array#values_at生成uniq的数组。

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

答案 1 :(得分:6)

一种解决方案是使用运动和类型构建某种键,如下所示:

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

uniq的工作方式是它使用块的返回值来比较元素。

答案 2 :(得分:4)

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