Difference between map and collect in Ruby?

后端 未结 6 1422
遥遥无期
遥遥无期 2020-11-28 00:26

I have Googled this and got patchy / contradictory opinions - is there actually any difference between doing a map and doing a collect on an array

6条回答
  •  醉酒成梦
    2020-11-28 01:13

    Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. (Ruby Monk)

    In other words, same source code :

                   static VALUE
    rb_ary_collect(VALUE ary)
    {
    long i;
    VALUE collect;
    
    RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
    collect = rb_ary_new2(RARRAY_LEN(ary));
    for (i = 0; i < RARRAY_LEN(ary); i++) {
        rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
    }
    return collect;
    }
    

    http://ruby-doc.org/core-2.2.0/Array.html#method-i-map

提交回复
热议问题