Comparing two arrays ignoring element order in Ruby

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

    You can actually implement this #compare method by monkey patching the Array class like this:

    class Array
      def compare(other)
        sort == other.sort
      end
    end
    

    Keep in mind that monkey patching is rarely considered a good practice and you should be cautious when using it.

    There's probably is a better way to do this, but that's what came to mind. Hope it helps!

提交回复
热议问题