Comparing two arrays ignoring element order in Ruby

后端 未结 8 565
春和景丽
春和景丽 2020-12-08 02:14

I need to check whether two arrays contain the same data in any order. Using the imaginary compare method, I would like to do:

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


        
8条回答
  •  孤城傲影
    2020-12-08 02:27

    You can open array class and define a method like this.

    class Array
      def compare(comparate)
        to_set == comparate.to_set
      end
    end
    
    arr1.compare(arr2)
    irb => true
    

    OR use simply

    arr1.to_set == arr2.to_set
    irb => true
    

提交回复
热议问题