两个列表中公共值的方法

发布于 2024-10-11 18:50:53 字数 281 浏览 6 评论 0原文

当我有 2 个数组(列表)并且我想获取一个仅包含两个数组共有的值的数组(列表)时,Ruby 是否有一个可以使用的方法?像这样......

a = [1,2,3]
b = [3,4,5]
=> the method would return [3]

反之亦然,这些数组(列表)中的值是“唯一的”。

a = [1,2,3]
b = [3,4,5]
=> the method would return [1,2,4,5]

Does Ruby has a method I could use when I have 2 arrays (lists) and I want to get an array (list) of only the values common to both arrays? Like this..

a = [1,2,3]
b = [3,4,5]
=> the method would return [3]

And the other way around, values that are "unique" in those arrays (lists).

a = [1,2,3]
b = [3,4,5]
=> the method would return [1,2,4,5]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不必了 2024-10-18 18:50:53
AND : a & b

Ruby 中没有数组的 XOR 方法,因此您可以通过其他方法来完成。这里有2种方法:

XOR : (a | b) - (a & b)
XOR : (a + b) - (a & b) # this result can have duplicates!

XOR : (a - b) | (b - a)
XOR : (a - b) + (b - a) # this result can have duplicates!
AND : a & b

There are no XOR method for arrays in Ruby, so you may do it via another methods. Here are 2 ways:

XOR : (a | b) - (a & b)
XOR : (a + b) - (a & b) # this result can have duplicates!

XOR : (a - b) | (b - a)
XOR : (a - b) + (b - a) # this result can have duplicates!
森林很绿却致人迷途 2024-10-18 18:50:53

您要查找的词是交集对称差。 AFAIK 在 Ruby 中是这样的:

[1,2,3] & [3,4,5] = [3]
[1,2,3] ^ [3,4,5] = [1,2,4,5]

The words you are looking for are intersection and symmetric difference. AFAIK it's this in Ruby:

[1,2,3] & [3,4,5] = [3]
[1,2,3] ^ [3,4,5] = [1,2,4,5]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文