如果所有哈希值具有相同的三把鑰匙,並沒有其他按鍵,它簡直是
new_array1 & new_array2
#=> [{:index=>4, :column=>0, :ID=>"ABC"},
# {:index=>4, :column=>2, :ID=>"BCD-1547"}]
如果哈希可能有其他的鍵,以及,你可以寫出如下。
new_array1 = [{:index=>4, :column=>0, :ID=>"ABC", :pet=>"cat"},
{:index=>4, :column=>1, :ID=>"XYZ", :bet=>"red"},
{:index=>4, :column=>2, :ID=>"BCD-1547", :met=>"Betty"}]
new_array2 = [{:index=>4, :column=>0, :ID=>"ABC", :tree=>"maple"},
{:index=>4, :column=>1, :ID=>"IJK", :colour=>"blue"},
{:index=>4, :column=>2, :ID=>"BCD-1547", :car=>"beemer"}]
keys = [:index,:column,:ID]
h1 = new_array1.each_with_object({}) { |g,h| h[g.select { |k,_| keys.include? k }] = g }
#=> {{:index=>4, :column=>0, :ID=>"ABC"}=>
# {:index=>4, :column=>0, :ID=>"ABC", :pet=>"cat"},
# {:index=>4, :column=>1, :ID=>"XYZ"}=>
# {:index=>4, :column=>1, :ID=>"XYZ", :bet=>"red"},
# {:index=>4, :column=>2, :ID=>"BCD-1547"}=>
# {:index=>4, :column=>2, :ID=>"BCD-1547", :met=>"Betty"}}
h2 = new_array2.each_with_object({}) { |g,h| h[g.select { |k,_| keys.include? k }] = g }
#=> {{:index=>4, :column=>0, :ID=>"ABC"}=>
# {:index=>4, :column=>0, :ID=>"ABC", :tree=>"maple"},
# {:index=>4, :column=>1, :ID=>"IJK"}=>
# {:index=>4, :column=>1, :ID=>"IJK", :colour=>"blue"},
# {:index=>4, :column=>2, :ID=>"BCD-1547"}=>
# {:index=>4, :column=>2, :ID=>"BCD-1547", :car=>"beemer"}}
(h1.keys & h2.keys).map { |k| [h1[k], h2[k]] }
#=> [[{:index=>4, :column=>0, :ID=>"ABC", :pet=>"cat"},
# {:index=>4, :column=>0, :ID=>"ABC", :tree=>"maple"}],
# [{:index=>4, :column=>2, :ID=>"BCD-1547", :met=>"Betty"},
# {:index=>4, :column=>2, :ID=>"BCD-1547", :car=>"beemer"}]]
1.考慮使用'each_with_object'和2.這有助於「'#做點什麼」? – mudasobwa
@mudasobwa他們可以迭代'res'做些事情,我會更新答案。 – Kris
這正是我要找的,謝謝! 你能解釋一下'注入([])'和'任何嗎?' – danynl