迭代一系列哈希并组合相似的元素

时间:2015-01-14 07:28:15

标签: ruby arrays hash

嗨,我有这个数组,例如

array = [
  {ingredients: [:t1, :t2], exp: 100, result: :t5}, 
  {ingredients: [:t3, :t4], exp: 200, result: :t10},
  {ingredients: [:t1, :t2], exp:  50, result: :t6}
]

我希望数组看起来像这样:

array = [
  {ingredients: [:t1, :t2], exp: 100, results: [:t5, :t6]},
  {ingredients: [:t3, :t4], exp: 200, results: [:t10]},
]

因此它应该检查数组中的每个元素,并结合包含相同成分数组的元素的所有结果。

我真的不知道从哪里开始,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

array = [ 
  {ingredients: [:t1, :t2], exp: 100, result: :t5},
  {ingredients: [:t3, :t4], exp: 200, result: :t10},
  {ingredients: [:t1, :t2], exp:  50, result: :t6}
]

array.reduce([]) { |memo, e|    # will build new array
  el = memo.find { |_e| _e[:ingredients] == e[:ingredients] }
  if el                         # already have same ingredients
    el[:results] << e[:result]   # modify 
    memo
  else
    e[:results] = [*e[:result]]  # append
    e.delete :result
    memo << e
  end 
}

#=> [
#  [0] {
#    :exp => 100,
#    :ingredients => [
#      [0] :t1,
#      [1] :t2
#    ],
#    :results => [
#      [0] :t5,
#      [1] :t6
#    ]
#  },
#  [1] {
#    :exp => 200,
#    :ingredients => [
#      [0] :t3,
#      [1] :t4
#    ],
#         :results => [
#      [0] :t10
#    ]
#  }
#]

希望它有所帮助。