确定一个数组是否包含ruby中另一个数组的内容

And*_*imm 8 ruby arrays

在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)

在这种情况下,它适用于任何元素.

  • 它也是1.8.7. (3认同)

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)

  • 我不认为这对于检查数字是否按给定顺序出现是准确的.例如,如果`correct_combination = [1,3,4]`那么`[1,5,8,2,3,4,5] .contain?(correct_combination)`返回true. (2认同)