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 :-)
The above solution
deletes all instances of elements in array
b
from arraya
.In some cases, you want the result to be
[1, 2, 3, 3, 5]
. That is, you don't want to delete all duplicates, but only the elements individually.You could achieve this by
test
The code works even when the two arrays are not sorted. In the example, the arrays are sorted, but this is not required.
You can subtract arrays in Ruby:
See the Array documentation.