0

my problem should be rather simple, but i didn't got it.

For example i have the following data from the database:

@user = User.all

then i have an other array of user

other_user = getting_them_from_somewhere_else

Now i iterate over the two arrays and check if some users are still in the database by checking for the emails:

@other_user.each do |o|
    @user.each do |u|
        if o["email"] == u["user_mail"]
            @user.delete(u)
            break
        end
    end

    ... do something with o ...
end

The method @user.delete(u) deletes the user from the database, but i just want to remove the object u from the array @user.

1
  • 1
    @user is not an array.. it's a collection to be sure, but an activerecord collection. You can iterate across it, and do a pile of things that may feel like an array. Don't think of it as an array. It will break your heart. Commented Jul 30, 2013 at 3:13

4 Answers 4

0

You can do vise versa

result_users = []
@other_user.each do |o|
    @user.each do |u|
        if o["email"] != u["user_mail"]
            result_users << u
        end
    end

    ... do something with o ...
end
here you should use result_users array which has the users you need
Sign up to request clarification or add additional context in comments.

Comments

0

You can use:

@other_user.each do |o|
   @user.delete_if{|u| u["email"] == o["email"]}
end

It's more simple, and didn't remove of database, only remove in array. =)

Comments

0

How about going the cheaper way... Less work.. create an array of the email addresses that you know about, and don't want anymore.

other_emails = @other_user.map{|o| sanitize(o["email"]) }
@users = User.where("email not in (  #{other_emails.join(',')}  )")

There are so many pluses to this approach.

  1. there is only one loop (the map), nothing embedded.
  2. there is only one array resize (the map). We aren't calling delete which is a heavy operation on an array.
  3. We only get records across the network that we care about. Pulling down 1 million records when you only care about a handful is silly. Strive to only read from the DB what you need.

Sometimes letting the database do things is just smarter.

Comments

0

I think you don't need to use @user.email, just:

  @users.delete_if {|user| @other_user.include? user}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.