gpt4 book ai didi

arrays - ruby 比较不同数组中哈希之间的值

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:32 25 4
gpt4 key购买 nike

我有两个不同的数组,每个数组都包含不同的哈希值。

new_array1 =    [
{:index=>4, :column=>0, :ID=>"ABC"},
{:index=>4, :column=>1, :ID=>"XYZ"},
{:index=>4, :column=>2, :ID=>"BCD-1547"}
]


new_array2 = [
{:index=>4, :column=>0, :ID=>"ABC"},
{:index=>4, :column=>1, :ID=>"IJK"},
{:index=>4, :column=>2, :ID=>"BCD-1547"}
]

我想比较 new_array1:ID 键的值与 new_array2 中的值,仅当 :index :column 值相同。

ie)   
if (new_array1[0][:index] == new_array2[0][:index]) and (new_array1[0][:column] == new_array2[0][:column])
if(new_array1[0][:ID] == new_array2[0][:ID])
# do something
end
end

有没有办法遍历两个数组中的所有哈希并找到匹配项?或者也许是在 ruby​​ 中使用更优雅的方式来做到这一点?

最佳答案

这将返回匹配哈希的数组:

res = new_array1.inject([]) { |memo, hash| memo << hash if new_array2.any? { |hash2| hash[:ID] == hash2[:ID] && hash[:index] == hash2[:index] && hash[:column] == hash2[:column] }; memo } 
# => [{:index=>4, :column=>0, :ID=>"ABC"}, {:index=>4, :column=>1, :ID=>"XYZ"}, {:index=>4, :column=>2, :ID=>"BCD-1547"}]

res.each do |hash|
# do something
end

如果 new_array1 中的项目与 中的任何项目具有相同的 indexcolumnID 键code>new_array2 它将包含在内。

如果这些是散列中唯一的键,您还可以通过使用 == 比较相等性来简化:

res = new_array1.inject([]) { |memo, hash| memo << hash if new_array2.any? { |hash2| hash == hash2 }; memo }

inject 方法,别名也称为 reduce,获取一个集合并从中创建一个新值,每次将 block 提供给 inject 被调用时,它被赋予集合的下一个元素和前一个 block 的返回值(第一次调用该 block 时,它被赋予传递给 inject 的种子值)。这允许您建立一个类似于递归的值。

这里有一些注入(inject)的例子:Need a simple explanation of the inject method

any? 方法将在给定 block 对任何给定集合元素返回 true 时立即返回 true。如果该 block 从不返回 true,则 any? 返回 false。所以:

[0,0,0,1,0].any? { |num| num == 1 } # => true
[0,0,0,0,0].any? { |num| num == 1 } # => false

关于arrays - ruby 比较不同数组中哈希之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39848360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com