-1

I have two arrays

main_array = [[0,[1,4,5]], [1,[4,6,8]], [2,[5,6,7,8]], [3,[9,8]], [4,[7,2]]]
other_array = [[1,4,5],[9,8]]

What I want to do is to delete those elements in main_array if it can be found in other_array. (Meaning I will be left with [[1,[4,6,8]], [2,[5,6,7,8]],[4,[7,2]]] ) So I did the following:

other_array.each { |x|
for i in 0..main_array.length-1
  main_array.delete(x)
}

It didn't work. Any clues on how I should approach this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2765163
  • 39
  • 1
  • 1
  • 8

2 Answers2

2
main_array.reject { |_,a| other_array.include?(a) }
  #=> [[1,[4,6,8]], [2,[5,6,7,8]], [4,[7,2]]] 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

You can use Enumerable#reject (this is a module that is included in almost all collections in Ruby, such as Arrays, Hashes, Sets and etc.), it returns new array with removed elements, based on some condition:

main_array.reject { |item| other_array.include? item[1] } 

Here item is every item in main_array. You can also "unwrap" your item if you want to control its elements individually:

main_array.reject { |(key, val)| other_array.include? val }

I'd recommend you to go and check the link above, there are also lots of interesting things over there.

Alexey Shein
  • 7,342
  • 1
  • 25
  • 38