3

I'm having some trouble figuring out the right way to do this:

I have an array and a separate array of arrays that I want to compare to the first array. The first array is a special Enumerable object that happens to contain an array.

Logic tells me that I should be able 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 it returns [] instead.

This idea works if I do this:

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

It will return

 => [2]

I can't assign the values to another object, as the [1,2,3] array must stay its special Enumerable object. I'm sure there is a much simpler explanation to this than what I'm trying. Anybody have any ideas?

3 Answers 3

2

You can also flatten the multi-dimensional array and use the Array#& intersection operator to get the same result:

# 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]
Sign up to request clarification or add additional context in comments.

Comments

1

Can't you just add the two inner array together, and and check the inclusion on the concatenated array?

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

3 Comments

This will not work as I have an arbitrary number of inner arrays.
Better [[2,4,5], [3,6,7]].flatten, then it works with any number of arrays.
Or [[2,4,5], [3,6,7,5]].flatten.uniq if there are possible duplicates in your arrays.
0

The problem is that the return value of each is the array being iterated over, not the boolean (which is lost). Since the array is truthy, the value returned back to delete_if is always true, so all elements are deleted. You should instead use any?:

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

3 Comments

This seems to have gotten me where I need to be. I knew I was over complicating it. Thanks!
select in stead of delete_if gets rid of the !.
@steenslag But select doesn't modify the array in place, whereas delete_if does, so it'd have to be select!.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.