instance method
Array#<=>
(untyped) -> ::Integer?
self <=> other_array → -1, 0, or 1
array.c
View on GitHub ↗
VALUE
rb_ary_cmp(VALUE ary1, VALUE ary2)
{
long len;
VALUE v;
ary2 = rb_check_array_type(ary2);
if (NIL_P(ary2)) return Qnil;
if (ary1 == ary2) return INT2FIX(0);
v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
if (!UNDEF_P(v)) return v;
len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
if (len == 0) return INT2FIX(0);
if (len > 0) return INT2FIX(1);
return INT2FIX(-1);
}
Returns -1, 0, or 1 as self is determined to be less than, equal to, or greater than other_array.
Iterates over each index i in (0...self.size):
-
Computes
result[i]asself[i] <=> other_array[i]. -
Immediately returns 1 if
result[i]is 1:Example[0, 1, 2] <=> [0, 0, 2] # => 1
-
Immediately returns -1 if
result[i]is -1:Example[0, 1, 2] <=> [0, 2, 2] # => -1
-
Continues if
result[i]is 0.
When every result is 0, returns self.size <=> other_array.size (see Integer#<=>):
Example
[0, 1, 2] <=> [0, 1] # => 1 [0, 1, 2] <=> [0, 1, 2] # => 0 [0, 1, 2] <=> [0, 1, 2, 3] # => -1
Note that when other_array is larger than self, its trailing elements do not affect the result:
Example
[0, 1, 2] <=> [0, 1, 2, -3] # => -1 [0, 1, 2] <=> [0, 1, 2, 0] # => -1 [0, 1, 2] <=> [0, 1, 2, 3] # => -1
Related: see Methods for Comparing.