Comparing two arrays ignoring element order in Ruby

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

    Use difference method if length of arrays are the same https://ruby-doc.org/core-2.7.0/Array.html#method-i-difference

    arr1 = [1,2,3]
    arr2 = [1,2,4]
    arr1.difference(arr2) # => [3]
    arr2.difference(arr1) # => [4]
    
    # to check that arrays are equal:
    arr2.difference(arr1).empty?
    

    Otherwise you could use

    # to check that arrays are equal:
    arr1.sort == arr2.sort
    
    0 讨论(0)
  • 2020-12-08 02:47

    The easiest way is to use intersections:

    @array1 = [1,2,3,4,5]
    @array2 = [2,3,4,5,1]
    

    So the statement

    @array2 & @array1 == @array2
    

    Will be true. This is the best solution if you want to check whether array1 contains array2 or the opposite (that is different). You're also not fiddling with your arrays or changing the order of the items. You can also compare the length of both arrays if you want them to be identical in size.

    It's also the fastest way to do it (correct me if I'm wrong)

    0 讨论(0)
提交回复
热议问题