在 Ruby 中从另一个数组中减去一个数组 [英] Subtracting one Array from another in Ruby
问题描述
我有两个任务数组 - 创建和分配.我想从创建的任务数组中删除所有分配的任务.这是我的工作,但凌乱的代码:
@assigned_tasks = @user.assigned_tasks@created_tasks = @user.created_tasks#不显示分配给自己的已创建任务@created_not_doing_tasks = Array.new@created_tasks.each 做 |task|除非@assigned_tasks.include?(task)@created_not_doing_tasks <<任务结尾结尾
我相信有更好的方法.它是什么?谢谢:-)
您可以在 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 的行为,参见库类 Set.
请参阅 Array 文档.
I've got two arrays of Tasks - created and assigned. I want to remove all assigned tasks from the array of created tasks. Here's my working, but messy, code:
@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
I'm sure there's a better way. What is it? Thanks :-)
You can subtract arrays in Ruby:
[1,2,3,4,5] - [1,3,4] #=> [2,5]
ary - other_ary → new_ary Array Difference
Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.
It compares elements using their hash and eql? methods for efficiency.
[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
If you need set-like behavior, see the library class Set.
See the Array documentation.
这篇关于在 Ruby 中从另一个数组中减去一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!