在ruby中,我如何测试一个数组不仅具有另一个数组的元素,而是以特定顺序包含它们?
correct_combination = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].function_name(correct_combination) # => false
[8, 10, 1, 2, 3, 4, 5, 9].function_name(correct_combination) # => true
Run Code Online (Sandbox Code Playgroud)
我尝试过使用include
,但这用于测试是否[1,2,3].include?(2)
真实.
Yos*_*ssi 14
您可以使用each_cons方法:
arr = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].each_cons(arr.size).include? arr
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它适用于任何元素.
saw*_*awa 10
我认为它可以简单地完成.
class Array
def contain? other; (self & other) == other end
end
correct_combination = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].contain?(correct_combination) # => false
[8, 10, 1, 2, 3, 4, 5, 9].contain?(correct_combination) # => true
Run Code Online (Sandbox Code Playgroud)