【问题标题】:Merge hash with array of hashes based on value in shared key根据共享键中的值将散列与散列数组合并
【发布时间】:2015-09-18 00:36:24
【问题描述】:

我从以下开始:

@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}]

【问题讨论】:

  • 我不确定您要做什么...为什么不简单地使用以下信息填充现有的 @todd 哈希(或副本):@prod = @todd.map {|h| h.merge(call_api h[:num] ) } ...假设 @987654326 @ 返回值就位的嘘声。您想要实现的差异是什么?
  • 所以我遇到的问题是发送 num 以调用 api,然后当结果哈希被填充时合并 @todd 哈希,以便每个匹配的 num 和正确的价格被合并使用正确的数字。这有意义吗?

标签: ruby-on-rails arrays ruby hash


【解决方案1】:
@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.

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 2021-02-04
    • 2017-06-16
    • 2015-12-15
    • 2011-07-26
    • 2018-02-10
    • 2013-06-17
    • 2023-03-24
    相关资源
    最近更新 更多