繁体   English   中英

根据共享密钥中的值将哈希与哈希数组合并

[英]Merge hash with array of hashes based on value in shared key

我从以下内容开始:

@prod = []
@num = []
@todd = [{:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49"}, 
{:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"445.94"}]

然后创建一个查找数组:

@todd.each do |x|  
  @num << x[:num]
end

然后使用查找数组通过一个将各种数据加载到结果中的API:

@num.each do |x|
call_api(x) #I left out the code that populates the variables below..
results = {:num => x,  
:vendor => vendor, :type => type, :color => @color, :image => hi_image
}
end

当上面的API调用完成后,我想将@todd数组和results数组合并到哈希的@prod数组中。 结果就是这样。

[{:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49",
:vendor => "Boss", :type => "Shoes", :color => "Blue", :image => boss.jpg}, 
{:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"34.49",
:vendor => "Converse", :type => "Shirt", :color => "Orange", 
:image => cons.jpg}]
@prod = []
@num = []
@todd = [
  {:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49"},
  {:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"445.94"}
]

@todd.each do |hash|
  serial_number = hash[:num]

  # EXTERNAL CALL TO API
  info = api_call(serial_number) #likely returns json
  # parse into new hash called results

  results = {
    :vendor => vendor,
    :type => type,
    :color => @color,
    :image => hi_image
  }

  @prod << hash.merge(results)
end

@prod
# after iteration, @prod will have all the information you are looking for.

暂无
暂无

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

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