0

I have one array in rails, which for the sake of simplicity, we shall say is

@users = current_account.users

I have several other arrays, which contains subsets of that first array. These look like this

@missing_genders = @users.select{ |u| u.gender.nil?}
@missing_reference = @users.select{ |u| u.reference_number.nil?}

I have a few others like this too. What I need is to produce a list of all the users who are NOT erroneous. so basically everyone in the first array, who does not exist in any of the other arrays?

thinking through it, I have

@main_array = [1,2,3,4,5]
@error_array_1 = [1]
@error_array_2 = [1,2,3]

And I am looking to generate

@final_array = [4,5]
Gareth Burrows
  • 1,142
  • 10
  • 22
  • possible duplicate of [Subtracting one Array from another in Ruby](http://stackoverflow.com/questions/1192186/subtracting-one-array-from-another-in-ruby) – AGS Jan 28 '15 at 14:04

2 Answers2

4

The answer is really easy, you want to subtract the error_arrays from the main array, like this:

@final_array = @main_array - @error_array_1 - @error_array_2
=> [4, 5]
Grych
  • 2,861
  • 13
  • 22
0

This is the way to do it if you have many arrays:

main_array = [1,2,3,4,5,6]
error_array_1 = [1]
error_array_2 = [1,2,3]
error_array_4 = [6]

p [main_array,error_array_1,error_array_2,error_array_4].reduce(:-) #=> [4, 5]
hirolau
  • 13,451
  • 8
  • 35
  • 47