danynl danynl - 1 year ago 77
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
keys in
vs the values in
only if the
values are the same.

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

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 Source

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

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 }