Search code examples
arraysrubyinclude

A proper way to do this array comparrison in Ruby?


if array a contains any numbers also found in array b, i want them gone from a.

if b.any?
  b.each do |asdf|
    if a.include?(asdf)
      a = a - [asdf]
    end
  end
end

Is this the most efficient way to do it?

UPDATE:

The answers are nice, but I've realized that the search brings back an array of People instances, @search_return. My problem is i've got 3 arrays of ids (integers): @event.a, @event.b, and @event.c which are ids of people who have already registered with the event in some capactity.

I want to take out the people who are already registered at the event from the search return, but unfortunately event.a event.b and event.c are just ids of the people, not the actual instances of the people. hence all this:

if instance.a.any?
  instance.a.each do |asdf|
    qwer = Qwer.find(asdf)
    if @search_return.include?(qwer)
      @search_return = @search_return - [qwer]
    end
  end
end  

if instance.b.any?
  instance.b.each do |asdf|
    qwer = Qwer.find(asdf)
    if @search_return.include?(qwer)
      @search_return = @search_return - [qwer]
    end
  end
end 

if instance.c.any?
  instance.c.each do |asdf|
    qwer = Qwer.find(asdf)
    if @search_return.include?(qwer)
      @search_return = @search_return - [qwer]
    end
  end
end 

which may be quite heavy on the database but it's a search that won't be performed too often


Solution

  • If your task is "remove all elements in a that also exist in b" then you can just subtract them:

    2.6.3 :002 > a = [1, 2, 3, 4]
     => [1, 2, 3, 4]
    2.6.3 :003 > b = [2, 3]
     => [2, 3]
    2.6.3 :004 > c = a - b
     => [1, 4]
    2.6.3 :005 >