如何检查一个多维 Ruby 数组中的元素是否存在于另一个多维 Ruby 数组中?
我试图确定一个多维数组中的元素是否存在于另一个类似结构的数组中。
suspects = [['Rod', 100], ['Jane', 75], ['Freddy', 125]]
criminals = [['Bill', 75], ['Ted', 50], ['Rod', 75]]
我正在寻找的答案要么是真,要么是假。 在上面的示例中,响应将为 true,因为 Rod 存在于两个数组中。 第二层数组中的整数值没有意义。
我如何以典型的 Ruby 式简洁方式编写这样的测试代码?
I am trying to determine if the an element in one multi-dimensional array exists in another similarly structured array.
suspects = [['Rod', 100], ['Jane', 75], ['Freddy', 125]]
criminals = [['Bill', 75], ['Ted', 50], ['Rod', 75]]
The response I am looking for is either true or false. In the example above the response would be true because Rod exists in both arrays. The integer value has in the second tier array has no bearing.
How would I code such a test in typically Ruby-like succinctness?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
像这样更快:
Faster like this:
sepp2k 打败了我,但我必须提交只是为了表明我们在实施方面有多接近:
我喜欢他使用any?,但认为内部块应该是内联的:)
sepp2k beat me to it, but i have to submit just to show how close we were in implementation:
I like his use of any?, but think the inner block should be inline :)
怎么样:
示例:
How about:
Sample:
我不一定推荐这个,但另一个单行选项(如果算上
require
则为两个)可能是这样的:它从每个项目的第一个元素构建数组,然后将其转换为
设置
。Set
有&
(相交)方法,我们查看结果的大小来得出答案。I'm not necessarily recommending this, but anther one-line option (two if you count the
require
) could be this:It builds arrays from the first element of each item then converts it to a
Set
.Set
has the&
(intersect) method and we look at the size of the result for our answer.