The comparison operator for arrays is <=>.
This compares two arrays, arr1 and arr2.
It returns -1 if arr1 is less than arr2, it returns 0 if arr1 and arr2 are equal, and it returns 1 if arr2 is greater than arr1.
It compares each item in one array with the corresponding item in the other.
When two values are not equal, the result of their comparison is returned.
In other words, if this comparison were made:
[0,10,20] <=> [0,20,20]
the value -1 would be returned.
This means the first array is "less than" the second, since the integer at index 1 of the first array (10) is less than the integer at index 1 in the second array (20).
If you want to make a comparison based on the array's length rather than the value of its elements, you can use the length method:
# Here [2,3,4].length is less than [1,2,3,4].length p([1,2,3].length<=>[1,2,3,4].length) #=> -1 p([2,3,4].length<=>[1,2,3,4].length) #=> -1
If you are comparing arrays of strings, then comparisons are made on the ASCII values of the characters that make up those strings.
If one array is longer than another and the elements in both arrays are equal, then the longer array is deemed to be "greater."
p([1,2,3]<=>[2,3,4]) #=> -1 (array 1 < array 2) p([2,3,4]<=>[1,2,3]) #=> 1 (array 1 > array 2) p([1,2,3,4]<=>[1,2,3]) #=> 1 (array 1 > array 2)all p([1,2,3,4]<=>[100,200,300]) #=> -1 (array 1 < array 2) p([1,2,3]<=>["1","2","3"]) #=> nil (invalid comparison) # from w ww. j ava 2 s. c om