Determine if one array contains all elements of another array

前端 未结 8 1894
闹比i
闹比i 2021-02-07 12:05

I need to tell if an array contains all of the elements of another array with duplicates.

[1,2,3].contains_all? [1,2]   #=> true
[1,2,3].contains_all         


        
8条回答
  •  猫巷女王i
    2021-02-07 12:28

    If you can't find a method, you can build one using ruby's include? method.

    Official documentation: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F

    Usage:

    array = [1, 2, 3, 4]
    array.include? 3       #=> true
    

    Then, you can do a loop:

    def array_includes_all?( array, comparision_array )
      contains = true
      for i in comparision_array do
        unless array.include? i
          contains = false
        end
      end
      return contains
    end
    
    array_includes_all?( [1,2,3,2], [1,2,2] )    #=> true
    

提交回复
热议问题