查找两个数组的共同点


75

有没有一种方法可以比较两个数组并显示它们的共同点?

array1 = ["pig", "dog", "cat"]
array2 = ["dog", "cat", "pig", "horse"]

我键入什么来显示["pig", "dog", "cat"]这两个数组之间的共同点?

Answers:


167

您可以使用&以下方法将数组相交:

array1 & array2

这将返回["pig", "dog", "cat"]


有关集合上的其他操作,例如联合和除法,请参见Set该类。
杰瑞德·贝克

5

设置相交。返回一个新数组,其中包含两个数组共有的元素,没有重复,例如:

["pig", "dog", "bird"] & ["dog", "cat", "pig", "horse", "horse"]
# => ["pig", "dog"]

您还可以阅读有关数组一致性的博客文章

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.