O Ruby Enumerable # zip cria matrizes internamente?
EmRuby - Compare dois enumeradores com elegância, foi dit
O problema com o zip é que ele cria matrizes internamente, independentemente do Enumerable que você passa. Há outro problema com o comprimento dos parâmetros de entrada
Eu dei uma olhada na implementação do Enumerable # zip no YARV e vi
static VALUE
enum_zip(int argc, VALUE *argv, VALUE obj)
{
int i;
ID conv;
NODE *memo;
VALUE result = Qnil;
VALUE args = rb_ary_new4(argc, argv);
int allary = TRUE;
argv = RARRAY_PTR(args);
for (i=0; i<argc; i++) {
VALUE ary = rb_check_array_type(argv[i]);
if (NIL_P(ary)) {
allary = FALSE;
break;
}
argv[i] = ary;
}
if (!allary) {
CONST_ID(conv, "to_enum");
for (i=0; i<argc; i++) {
argv[i] = rb_funcall(argv[i], conv, 1, ID2SYM(id_each));
}
}
if (!rb_block_given_p()) {
result = rb_ary_new();
}
/* use NODE_DOT2 as memo(v, v, -) */
memo = rb_node_newnode(NODE_DOT2, result, args, 0);
rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
return result;
}
Estou entendendo os seguintes bits corretament
Verifique se todos os argumentos são matrizes e, se houver, substitua alguma referência indireta à matriz por uma referência direta
for (i=0; i<argc; i++) {
VALUE ary = rb_check_array_type(argv[i]);
if (NIL_P(ary)) {
allary = FALSE;
break;
}
argv[i] = ary;
}
Se não forem todas as matrizes, crie um enumerador em vez
if (!allary) {
CONST_ID(conv, "to_enum");
for (i=0; i<argc; i++) {
argv[i] = rb_funcall(argv[i], conv, 1, ID2SYM(id_each));
}
}
Crie uma matriz de matrizes apenas se um bloco não for fornecido
if (!rb_block_given_p()) {
result = rb_ary_new();
}
Se tudo for uma matriz, usezip_ary
, caso contrário, usezip_i
e chame um bloco em cada conjunto de valores
/* use NODE_DOT2 as memo(v, v, -) */
memo = rb_node_newnode(NODE_DOT2, result, args, 0);
rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
Retorne uma matriz de matrizes se nenhum bloco for fornecido; caso contrário, retorne nil Qnil
)?
return result;
}