87

我有两个任务数组 - 创建和分配。我想从创建的任务数组中删除所有分配的任务。这是我的工作,但混乱的代码:

    @assigned_tasks = @user.assigned_tasks
    @created_tasks = @user.created_tasks

    #Do not show created tasks assigned to self
    @created_not_doing_tasks = Array.new
    @created_tasks.each do |task|
        unless @assigned_tasks.include?(task)
            @created_not_doing_tasks << task
        end
    end

我确信有更好的方法。它是什么?谢谢 :-)

4

2 回答 2

181

您可以在 Ruby 中减去数组:

[1,2,3,4,5] - [1,3,4]  #=> [2,5]

ary - other_ary → new_ary 数组差异

返回一个新数组,它是原始数组的副本,删除也出现在 other_ary 中的所有项。顺序从原始数组中保留。

它使用它们的哈希和 eql 比较元素?效率的方法。

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]

如果您需要类似集合的行为,请参阅库类 Set。

请参阅阵列文档。

于 2009-07-28T06:16:53.710 回答
12

上述解决方案

a - b

b从数组中删除数组中元素的所有实例a

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]

在某些情况下,您希望结果为[1, 2, 3, 3, 5]. 也就是说,您不想删除所有重复项,而只删除单个元素。

你可以通过

class Array
  def delete_elements_in(ary)
    ary.each do |x|
      if index = index(x)
        delete_at(index)
      end
    end
  end
end

测试

irb(main):198:0> a = [ 1, 1, 2, 2, 3, 3, 4, 5 ]
=> [1, 1, 2, 2, 3, 3, 4, 5]
irb(main):199:0> b = [ 1, 2, 4 ]
=> [1, 2, 4]
irb(main):200:0> a.delete_elements_in(b)
=> [1, 2, 4]
irb(main):201:0> a
=> [1, 2, 3, 3, 5]

即使两个数组未排序,该代码也可以工作。在示例中,数组已排序,但这不是必需的。

于 2017-09-15T16:49:07.903 回答