How to check if array shares elements with another array in Ruby?

Viewed 1188

I'm currently trying to see if an array of records shares elements with another array.

I'm using the splat operator for a conditional like this:

if @user.tags.include?(*current_tags)
    # code
end

This works when tags are present, but returns this error when current_tags are empty.

wrong number of arguments (given 0, expected 1)

This happens a lot in my app so I was wondering if there are any alternatives to achieving this same functionality but in other way that won't blow up if current_tags is an empty array.

3 Answers

You can use an intersection to solve this problem instead. The intersection of two arrays is an array containing only the elements present in both. If the intersection is empty, the arrays had nothing in common, else the arrays had the elements from the result in common:

if (current_tags & @user.tags).any?
  # ok
end

Another trick to do the same is:

if current_tags.any? { |tag| @user.tags.include?(tag) }
  ...
end

if you want to be sure that at least one of the current_tags is in the array of @user.tags, or

if current_tags.all? { |tag| @user.tags.include?(tag) }
  ...
end

in case all tags should be there.

Works fine with empty current_tags as well.

Add one more condition if current_tags.present?

if current_tags.present? && @user.tags.include?(*current_tags)
    # code
end

As

2.3.1 :002 > [].present?
 => false 
Related