当唯一ID匹配时,将键值对添加到哈希数组 [英] Add key value pair to Array of Hashes when unique Id's match

查看:116
本文介绍了当唯一ID匹配时,将键值对添加到哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个哈希数组

sent_array = [{:sellersku=>"0421077128", :asin=>"B00ND80WKY"},
{:sellersku=>"0320248102", :asin=>"B00WTEF9FG"}, 
{:sellersku=>"0324823180", :asin=>"B00HXZLB4E"}]

active_array = [{:price=>39.99, :asin1=>"B00ND80WKY"}, 
{:price=>7.99, :asin1=>"B00YSN9QOG"}, 
{:price=>10, :asin1=>"B00HXZLB4E"}]

我想遍历send_array,并找到:asin中的值等于active_array中:asin1中的值的位置,然后复制键& :price的值到send_array.结果:

I want to loop through sent_array, and find where the value in :asin is equal to the value in :asin1 in active_array, then copy the key & value of :price to sent_array. Resulting in this:

final_array = [{:sellersku=>"0421077128", :asin=>"B00ND80WKY", :price=>39.99},
{:sellersku=>"0320248102", :asin=>"B00WTEF9FG"}, 
{:sellersku=>"0324823180", :asin=>"B00HXZLB4E", :price=>10}]

我尝试了此操作,但遇到TypeError-没有将Symbol隐式转换为Integer(TypeError)

I tried this, but I get a TypeError - no implicit conversion of Symbol into Integer (TypeError)

sent_array.each do |x|
 x.detect { |key, value| 
  if value == active_array[:asin1]
    x[:price] << active_array[:price]
  end
 }
end

推荐答案

出于效率和可读性的考虑,首先在active_array上构建查找哈希是有意义的:

For reasons of both efficiency and readability, it makes sense to first construct a lookup hash on active_array:

h = active_array.each_with_object({}) { |g,h| h[g[:asin1]] = g[:price] } 
  #=> {"B00ND80WKY"=>39.99, "B00YSN9QOG"=>7.99, "B00HXZLB4E"=>10}

我们现在仅浏览sent_array,更新哈希值:

We now merely step through sent_array, updating the hashes:

sent_array.each { |g| g[:price] = h[g[:asin]] if h.key?(g[:asin]) }
  #=> [{:sellersku=>"0421077128", :asin=>"B00ND80WKY", :price=>39.99},
  #    {:sellersku=>"0320248102", :asin=>"B00WTEF9FG"}, 
  #    {:sellersku=>"0324823180", :asin=>"B00HXZLB4E", :price=>10}] 

从哈希(h)检索键值对比在散列数组中搜索键值对要快得多.

Retrieving a key-value pair from a hash (h) is much faster, of course, than searching for a key-value pair in an array of hashes.

这篇关于当唯一ID匹配时,将键值对添加到哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆