17

假设我有以下 Ruby 代码:

array_1 = ['a', 'b']
array_2 = ['a', 'b', 'c']

some_function(array_1, array_2) # => True
some_function(array_2, array_1) # => False
some_function(['a', 'b'], ['a', 'd']) # => False
some_function(['x', 'y'], array_2) # => False

当参数 2 包含参数 1 中的所有元素时,我非常希望some_function返回 True 。

4

3 回答 3

42
def f a,b
    (a-b).empty?
end
于 2010-10-09T19:21:59.003 回答
1

从之前的帖子来看,

def f a,b
    (a-b).empty?
end

不会按您期望的方式工作,例如:

a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a2 = [2, 3, 5, 9]

(a1-a2).empty? # returns true

然而,

a1-a2 # returns [1, 4, 6, 7, 8], not empty

因此f返回假。

如果您想要单线,更准确的解决方案是:

def f a,b
    a&b == b
end

a&b将返回两者中的所有元素,a然后b我们检查是否等于b

为了模棱两可:

def f a,b
    (a&b == a) || (a&b == b)
end
于 2015-10-14T21:32:58.590 回答
-2
def f a,b
    tmp  = a.map(|i| b.include?(i))
    tmp.include?(false)
end
于 2012-12-31T09:09:24.200 回答