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

前端 未结 11 1021
清歌不尽
清歌不尽 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:54

    I would like to consider continuous sequence of elements from other array in container array and present this:-- code is inspired from the Sawa's code

    class Array
      def contain? other
       arr = self & other
       (arr.eql? other ) && ((self.index(arr.last) - self.index(arr.first)).eql?(other.size - 1))
      end
    end
    

    Result:--

    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
    [1, 8, 2, 3, 4, 5].contain?(correct_combination) # => false
    

提交回复
热议问题