4

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
  • this will only work if current_tags has exactly 1 element. I would recommend not using include? here Commented Oct 24, 2018 at 5:29
  • 1
    What's the expected behavior if current_tags is empty – should the conditional evaluate or skip the code block in that case? Commented Oct 24, 2018 at 6:24
  • Possible duplicate of Finding what is common to two arrays Commented Oct 25, 2018 at 7:59

3 Answers 3

17

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
Sign up to request clarification or add additional context in comments.

1 Comment

All the answers were good, but this is the simplest, easiest to understand. Thanks.
4

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.

Comments

0

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 

1 Comment

This doesn't work if current_tags has more than 1 element - include? takes 1 and only 1 arg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.