public Method

Array.<=>(p1)

array <→ other_array     -1, 0, +1

Comparison—Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array. Each object in each array is compared (using <=>). If any value isn’t equal, then that inequality is the return value. If all the values found are equal, then the return is based on a comparison of the array lengths. Thus, two arrays are ``equal’’ according to Array#<=> if and only if they have the same length and the value of each element is equal to the value of the corresponding element in the other array.

[ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
[ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1

Source Code

/* 
*  call-seq:
*     array <=> other_array   ->  -1, 0, +1
*
*  Comparison---Returns an integer (-1, 0,
*  or +1) if this array is less than, equal to, or greater than
*  other_array.  Each object in each array is compared
*  (using <=>). If any value isn't
*  equal, then that inequality is the return value. If all the
*  values found are equal, then the return is based on a
*  comparison of the array lengths.  Thus, two arrays are
*  ``equal'' according to <code>Array#<=></code> if and only if they have
*  the same length and the value of each element is equal to the
*  value of the corresponding element in the other array.
*  
*     [ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
*     [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1
*
*/

VALUE
rb_ary_cmp(ary1, ary2)
   VALUE ary1, ary2;
{
   long i, len;

   ary2 = to_ary(ary2);
   len = RARRAY(ary1)->len;
   if (len > RARRAY(ary2)->len) {
       len = RARRAY(ary2)->len;
   }
   for (i=0; i<len; i++) {
       VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i));
       if (v != INT2FIX(0)) {
           return v;
       }
   }
   len = RARRAY(ary1)->len - RARRAY(ary2)->len;
   if (len == 0) return INT2FIX(0);
   if (len > 0) return INT2FIX(1);
   return INT2FIX(-1);
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.