public Method

Array.flatten!

array.flatten!  array or nil

Flattens self in place. Returns nil if no modifications were made (i.e., array contains no subarrays.)

a = [ 1, 2, [3, [4, 5] ] ]
a.flatten!   #=> [1, 2, 3, 4, 5]
a.flatten!   #=> nil
a            #=> [1, 2, 3, 4, 5]

Source Code

/*
*  call-seq:
*     array.flatten! -> array or nil
*  
*  Flattens _self_ in place.
*  Returns <code>nil</code> if no modifications were made (i.e.,
*  <i>array</i> contains no subarrays.)
*     
*     a = [ 1, 2, [3, [4, 5] ] ]
*     a.flatten!   #=> [1, 2, 3, 4, 5]
*     a.flatten!   #=> nil
*     a            #=> [1, 2, 3, 4, 5]
*/

static VALUE
rb_ary_flatten_bang(ary)
   VALUE ary;
{
   long i = 0;
   int mod = 0;
   VALUE memo = Qnil;

   while (i<RARRAY(ary)->len) {
       VALUE ary2 = RARRAY(ary)->ptr[i];
       VALUE tmp;

       tmp = rb_check_array_type(ary2);
       if (!NIL_P(tmp)) {
           if (NIL_P(memo)) {
               memo = rb_ary_new();
           }
           i += flatten(ary, i, tmp, memo);
           mod = 1;
       }
       i++;
   }
   if (mod == 0) return Qnil;
   return ary;
}
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.