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

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

    This is the best I could come up with. All the return calls are a bit ugly, but it should be quicker than doing a string comparison if it's large arrays.

    class Array
      def same?(o)
        if self.size == o.size
          (0..self.size).each {|i| return false if self[i] != o[i] }
        else
          return false
        end
    
        return true
      end
    end
    
    a = [1,2,3,4,5]
    b = [1, 5, 8, 2, 3, 4, 5]
    c = [1, 2, 6, 4, 5]
    
    puts a.same?(a.reverse) # => false
    puts a.same?(a) # => true
    puts a.same?(b) # => false
    puts a.same?(c) # => false
    

提交回复
热议问题