Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 524
Alvaro Alday Avatar asked Oct 28 '25 13:10

Alvaro Alday


2 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
like image 200
d11wtq Avatar answered Oct 30 '25 07:10

d11wtq


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.

like image 34
Ilya Konyukhov Avatar answered Oct 30 '25 05:10

Ilya Konyukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!