我想合并两个列表。一个是活动记录列表,另一个是简单列表。
每个对象在合并后都会获得权重属性。
我怎么能以更优雅的方式做到这一点。
a_list = [
{name: "Jack", age: 19},
{name: "Mark", age: 29},
]
weights = [ 38, 19
]
a_list.join(b_list) = [
{name: "Jack", age: 19, weight: 38},
{name: "Mark", age: 29, weight: 19},
]
weights.each_with_index do |value, i|
a_list[i]["weight"] = value
end
答案 0 :(得分:2)
做你的传统方法"作用:
weights.zip(a_list).zip{|value, h| h["weight"] = value}
要获得上面代码中a_list.join(b_list)
所拥有的内容:
weights.zip(a_list).zip{|value, h| h[:weight] = value}
答案 1 :(得分:0)
a_list.map.with_index { |x, i| x.merge(weight: weights[i]) }
# => [{:name=>"Jack", :age=>19, :weight=>38}, {:name=>"Mark", :age=>29, :weight=>19}]