Search code examples
rubyarraysarray-difference

Subtracting one Array from another in Ruby


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 :-)


Solution

  • 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.