s c
s c

Reputation: 71

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

Upvotes: 0

Views: 151

Answers (2)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

I think you want something like this

arr1.select{|el| ( el & arr2.flatten ).empty? }

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110755

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

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

Upvotes: 0

Related Questions