如何确定一个数组是否包含另一个数组的所有元素 [英] How to determine if one array contains all elements of another array

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

问题描述

给定:

a1 = [5, 1, 6, 14, 2, 8]

我想确定它是否包含以下所有元素:

I would like to determine if it contains all elements of:

a2 = [2, 6, 15]

在这种情况下,结果是false.

In this case the result is false.

是否有任何内置的 Ruby/Rails 方法来识别此类数组包含?

Are there any built-in Ruby/Rails methods to identify such array inclusion?

实现这一点的一种方法是:

One way to implement this is:

a2.index{ |x| !a1.include?(x) }.nil?

有没有更好、更易读的方法?

Is there a better, more readable, way?

推荐答案

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

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

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