danynl danynl - 1 month ago 8
Ruby Question

ruby Compare values between hashes in different arrays

I have two different arrays, each consisting of different hashes.

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


I want to compare the values of the
:ID
keys in
new_array1
vs the values in
new_array2
only if the
:index
and
:column
values are the same.

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


Is there a way to loop through all the hashes in both arrays and find the match? Or perhaps a more elegant way to do this in ruby?

Answer

This will return an array of matching hashes:

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

If an item in new_array1 has the same index, column and ID keys as any item in new_array2 it will be included.

You could also simply if these are the only keys:

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