如何通过其中一个哈希键值合并两个哈希数组



我有两个散列数组:

[{:status=>"failed", :tag=>"tag156", :node=>"isfw-a"},
{:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a"},
{:status=>"changed", :tag=>"tag156", :node=>"vpfw-a"}]
[{:status=>"success", :sender=>"ayfw-a"},
{:status=>"success", :sender=>"vpfw-a"}]

我可以用来合并的键是:node:sender。我需要将第二个数组中的:status参数添加到第一个数组中,作为:another_status,在第二个阵列中没有相应:sender的地方放入"跳过",如下所示:

[{:status=>"failed", :tag=>"tag156", :node=>"isfw-a", :another_status=>"skipped"},
{:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a", :another_status=>"success"},
{:status=>"changed", :tag=>"tag156", :node=>"vpfw-a", :another_status=>"success"}]

我无法想出实现这一点的解决方案。

可能是这样的吗?

a1 = [
  {:status=>"failed", :tag=>"tag156", :node=>"isfw-a"},
  {:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a"},
  {:status=>"changed", :tag=>"tag156", :node=>"vpfw-a"},
]
a2 = [
  {:status=>"success", :sender=>"ayfw-a"},
  {:status=>"success", :sender=>"vpfw-a"},
]
sender_status = Hash[ a2.map { |item| [ item[:sender], item[:status] ] } ]
a1.each do |item|
  item[:another_status] = sender_status[item[:node]] || 'skipped'
end
a1.each { |item| p item }

输出

{:status=>"failed", :tag=>"tag156", :node=>"isfw-a", :another_status=>"skipped"}
{:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a", :another_status=>"success"}
{:status=>"changed", :tag=>"tag156", :node=>"vpfw-a", :another_status=>"success"}
a1 = [{:status=>"failed", :tag=>"tag156", :node=>"isfw-a"},
{:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a"},
{:status=>"changed", :tag=>"tag156", :node=>"vpfw-a"}]
a2 = [{:status=>"success", :sender=>"ayfw-a"},
{:status=>"success", :sender=>"vpfw-a"}]
a1.map do |h1| h1.merge(another_status:
  a2.find{|h2| h2[:sender] == h1[:node]}.to_h[:status] || "skipped"
) end

输出

[
  {
    :status         => "failed",
    :tag            => "tag156",
    :node           => "isfw-a",
    :another_status => "skipped"
  },
  {
    :status         => "unchanged",
    :tag            => "tag156",
    :node           => "ayfw-a",
    :another_status => "success"
  },
  {
    :status         => "changed",
    :tag            => "tag156",
    :node           => "vpfw-a",
    :another_status => "success"
  }
]
ar1 = [ {:status=>"failed", :tag=>"tag156", :node=>"isfw-a"},
        {:status=>"unchanged", :tag=>"tag156", :node=>"ayfw-a"},
        {:status=>"changed", :tag=>"tag156", :node=>"vpfw-a"}]
ar2 = [{:status=>"success", :sender=>"ayfw-a"},
       {:status=>"success", :sender=>"vpfw-a"}]
new_hsh = ar1.map do |a1| 
  bol = ar2.select{|a2| a2[:sender] == a1[:node] }
  bol ? a1[:another_status]=bol[:status] : a1[:another_status]= 'skipped'
  a1
end
new_ary
# => [{:status=>"failed",
#      :tag=>"tag156",
#      :node=>"isfw-a",
#      :another_status=>"skipped"},
#     {:status=>"unchanged",
#      :tag=>"tag156",
#      :node=>"ayfw-a",
#      :another_status=>"success"},
#     {:status=>"changed",
#      :tag=>"tag156",
#      :node=>"vpfw-a",
#      :another_status=>"success"}]

最新更新