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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With