Ruby,数组中基于多个字段的唯一哈希
我想返回一个基于sport和type组合的哈希数组 我得到了以下数组:Ruby,数组中基于多个字段的唯一哈希,ruby,arrays,Ruby,Arrays,我想返回一个基于sport和type组合的哈希数组 我得到了以下数组: [ { 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: "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 },
]
我尝试使用(伪代码):
我知道我可以用循环创建这样的数组,我对ruby很陌生,我很好奇是否有更好(更优雅)的方法来实现它。一个解决方案是用运动和类型构建某种类型的键,如下所示:
arr.uniq{ |m| "#{m[:sport]}-#{m[:type]}" }
其工作方式是使用块的返回值来比较元素。尝试使用生成一个数组以uniq
by
sports.uniq{ |s| s.values_at(:sport, :type) }
是的,带块的
uniq
是一种方法,但还有另一种方法:arr.group\u by{h |[h[:sport],h[:type]]}.values.map(&:first)
。只是一个小小的更正:uniq
将每个值传递给块,因此在这种情况下实际上是一个散列,它将被调用。如果你有一个数组而不是散列或数组,那就要小心了。
sports.uniq{ |s| s.values_at(:sport, :type) }
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}]