如何确定一个数组是否包含另一个数组的所有元素 [英] How to determine if one array contains all elements of another array
本文介绍了如何确定一个数组是否包含另一个数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:
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屋!
查看全文