从对象数组中删除对象

时间:2012-01-21 15:32:43

标签: arrays ruby-on-rails-3

我的问题应该相当简单,但我没有得到它。

例如,我有来自数据库的以下数据:

@user = User.all

然后我有另一个用户数组

other_user = getting_them_from_somewhere_else

现在我遍历两个数组并通过检查电子邮件检查一些用户是否仍在数据库中:

@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

方法@ user.delete(u)从数据库中删除用户,但我只是想从数组@user中删除对象。

4 个答案:

答案 0 :(得分:0)

你可以反其道而行

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

答案 1 :(得分:0)

您可以使用:

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

它更简单,并没有删除数据库,只删除数组。 =)

答案 2 :(得分:0)

如何以更便宜的方式......减少工作量...... 创建一个您知道的电子邮件地址数组,不再需要了。

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

这种方法有很多优点。

  1. 只有一个循环(地图),没有任何嵌入。
  2. 只有一个数组调整大小(地图)。我们没有调用对数组进行繁重操作的删除。
  3. 我们只会通过网络获取我们关心的记录。当你只关心少数时,减少100万条记录是愚蠢的。努力只从DB中读取您需要的内容。
  4. 有时让数据库做事情更聪明。

答案 3 :(得分:0)

我认为您不需要使用@ user.email,只需:

  @users.delete_if {|user| @other_user.include? user}
相关问题