Determining whether one array contains the contents of another array in ruby

前端 未结 11 1023
清歌不尽
清歌不尽 2021-02-09 03:06

In ruby, how do I test that one array not only has the elements of another array, but contain them in that particular order?

correct_combination = [1, 2, 3, 4, 5         


        
11条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 03:43

    A really quick way to do this is to simply subtract one array from the other and test for an empty array.

    correct_combination = [1, 2, 3, 4, 5]
    yep = [8, 10, 1, 2, 3, 4, 5, 9]
    nope = [1, 8, 2, 3, 4]
    if correct_combination - yep == []
      puts "yep has all the values"
    end
    if correct_combination - nope == []
      puts "nope has all the values"
    end
    

    This approach does not care about position so delete away!

    Sorry... I missed the point to the question as well. Didn't realize you were looking for order of precedence. I came across this when looking for a solution to evaluating if one large array contained all the entries of another large array. The .all?/include? approach takes a really long time to complete. Good luck!

提交回复
热议问题