我想根据运动和类型组合取回一系列哈希
我有以下数组:
[
{ 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很新,我很好奇是否有更好(更优雅)的方法。
答案 0 :(得分:16)
尝试使用Array#values_at生成uniq
的数组。
sports.uniq{ |s| s.values_at(:sport, :type) }
答案 1 :(得分:6)
答案 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}]