简体   繁体   English

从哈希数组中的每个组中获取第二项的聪明方法?

[英]Clever Way To Get 2nd Item From Each Group In Array Of Hashes?

The problem would be easy to solve with a manual loop and a result array, which you add onto as you go. 使用手动循环和结果数组很容易解决该问题,您可以随时将其添加到其中。 But I'm looking for a more ruby-esque solution, probably something that uses inject or select. 但是我正在寻找更像红宝石的解决方案,可能是使用注入或选择的解决方案。 Here's the problem: 这是问题所在:

arr_of_hashes = [
  {id: 1, val: "blah1"},
  {id: 1, val: "blah2"},
  {id: 1, val: "blah3"},
  {id: 2, val: "blah4"},
  {id: 2, val: "blah5"},
  {id: 3, val: "blah6"},
  {id: 3, val: "blah7"},
  {id: 3, val: "blah8"},
  {id: 3, val: "blah9"}
]

"Groups" are defined by the "id" field in the hashes. “组”由哈希中的“ id”字段定义。 We are guaranteed each group has at least two items. 我们保证每个小组至少有两个项目。 We want to return an array containing the 2nd item of each group: 我们要返回一个包含每个组的第二项的数组:

output_should_be = [
  {id: 1, val: "blah2"},
  {id: 2, val: "blah5"},
  {id: 3, val: "blah7"}
]

"I'm looking for a more ruby-esque solution". “我正在寻找更像红宝石的解决方案”。 I guess you mean functional : 我猜你的意思是功能性的

arr_of_hashes.chunk { |h| h[:id] }.map { |id, hs| hs[1] }
#=> [{:id=>1, :val=>"blah2"}, {:id=>2, :val=>"blah5"}, {:id=>3, :val=>"blah7"}]

Use group_by if elements are not pre-ordered by id . 如果元素未按id排序,请使用group_by

这是使用group_by的解决方案:

arr_of_hashes.group_by{|h| h[:id]}.to_a.map{|id,a| a[1]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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