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

时间:2015-07-01 01:58:22

标签: ruby-on-rails arrays ruby hash

我从以下开始:

@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数组和结果数组合并到@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}]

1 个答案:

答案 0 :(得分:0)

@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.