Comparing two arrays ignoring element order in Ruby

后端 未结 8 561
春和景丽
春和景丽 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:34

    The most elegant way I have found:

    arr1 = [1,2,3,5,4]
    arr2 = [3,4,2,1,5]
    arr3 = [3,4,2,1,5,5]
    
    
    (arr1 - arr2).empty? 
    => true
    
    (arr3 - arr2).empty?
    => false
    

提交回复
热议问题