Looping over an array

I am having trouble setting it up correctly:

I have an array and a separate array of arrays that I want to compare with the first array. The first array is a special object Enumerablethat contains an array.

Logic tells me that I have to do this:

[1,2,3].delete_if do |n|
  [[2,4,5], [3,6,7]].each do |m|
    ! m.include?(n)
  end
end

Which I would expect to return => [2,3]

But instead, it returns [].

This idea works if I do this:

[1,2,3].delete_if do |n|
  ! [2,4,5].include?(n)
end

He will return

 => [2]

I cannot assign values ​​to another object, since the array [1,2,3]must remain a special object Enumerable. I am sure there is a much simpler explanation for this than what I am trying. Does anyone have any ideas?

+3
source share
3 answers

, each - , , ( ). , , delete_if, , . any?:

[1,2,3].delete_if do |n|
  ![[2,4,5], [3,6,7]].any? do |m|
    m.include?(n)
  end
end
#=> [2, 3]
0

Array # &, :

# cast your enumerable to array with to_a
e = [1,2,3].each
e.to_a & [[2,4,5], [3,6,7]].flatten
# => [2, 3]
+2

Can't you just add two internal arrays together and check for inclusion in a concatenated array?

[1,2,3].delete_if do |n|
  !([2,4,5] + [3,6,7]).include?(n)
end
+1
source

All Articles