简体   繁体   English

如何检查数组是否与Ruby中的另一个数组共享元素?

[英]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: 我正在将splat运算符用于这样的条件:

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

This works when tags are present, but returns this error when current_tags are empty. 存在标签时此方法有效,但当current_tags为空时返回此错误。

wrong number of arguments (given 0, expected 1) 参数数目错误(给定0,应为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. 这种情况在我的应用程序中经常发生,所以我想知道是否有其他替代方法可以实现相同的功能,但是如果current_tags是一个空数组,则不会以其他方式current_tags

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 如果您想确保current_tags中至少有一个位于@user.tags数组中,或者

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. 与空的current_tags也很好。

Add one more condition if current_tags.present? 如果current_tags.present?加入更多条件current_tags.present?

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

As

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM