如何检查 Ruby 数组是否包含多个值之一? [英] How can I check if a Ruby array includes one of several values?

查看:25
本文介绍了如何检查 Ruby 数组是否包含多个值之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Ruby 数组,我需要查看它们是否有任何共同的值.我可以循环遍历一个数组中的每个值,然后在另一个数组中执行 include?() ,但我确信有更好的方法.它是什么?(数组都保存字符串.)

I have two Ruby arrays, and I need to see if they have any values in common. I could just loop through each of the values in one array and do include?() on the other, but I'm sure there's a better way. What is it? (The arrays both hold strings.)

谢谢.

推荐答案

设置相交 他们:

a1 & a2

这是一个例子:

> a1 = [ 'foo', 'bar' ]
> a2 = [ 'bar', 'baz' ]
> a1 & a2
=> ["bar"]
> !(a1 & a2).empty? # Returns true if there are any elements in common
=> true

这篇关于如何检查 Ruby 数组是否包含多个值之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆