s c s c - 3 months ago 23
Ruby Question

Ruby 2D array comparison

We have a 2D array as follows where A, B etc are the literals [string values]:

arr1 = [["A","B"], ["C","D"], ["E","F"], ["G","H"]]


now i want to compare this
arr1
with another array and remove the matching elements in the array, the other array is follows:

arr2 = [["C"], ["F"]]


i want to make sure that if any of the element matches with the element in
arr1
, the corresponding element should be removed from the
arr1
and output should be as follows:

output = [["A","B"], ["G","H"]]

Answer
a2 = arr2.flatten
  #=> ["C", "F"] 

arr1.reject { |a| (a & a2).any? } 
  #=> [["A", "B"], ["G", "H"]]
Comments