Ruby: Array contained in Array, any order [duplicate]

折月煮酒 提交于 2019-11-29 03:16:39
def f a,b
    (a-b).empty?
end

From a previous post,

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

will not work the way you expect, for example:

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

(a1-a2).empty? # returns true

however,

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

thus f returns false.

A more accurate solution, if you want a one-liner would be:

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

a&b will return all elements that are in both a and b then we check to see if that is equal to b

For ambiguity sake:

def f a,b
    (a&b == a) || (a&b == b)
end
def f a,b
    tmp  = a.map(|i| b.include?(i))
    tmp.include?(false)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!