ruby-changes:52576
From: nobu <ko1@a...>
Date: Thu, 20 Sep 2018 12:18:57 +0900 (JST)
Subject: [ruby-changes:52576] nobu:r64788 (trunk): Introduce rb_ary_union method in Array
nobu 2018-09-20 12:18:53 +0900 (Thu, 20 Sep 2018) New Revision: 64788 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=64788 Log: Introduce rb_ary_union method in Array Avoid repeating code and improve readability in `rb_ary_or` and `rb_ary_union_multi`. [Fix GH-1747] [Feature #14097] From: Ana Mar?\195?\173a Mart?\195?\173nez G?\195?\179mez <ammartinez@s...> Modified files: trunk/array.c Index: array.c =================================================================== --- array.c (revision 64787) +++ array.c (revision 64788) @@ -4271,6 +4271,17 @@ ary_hash_orset(st_data_t *key, st_data_t https://github.com/ruby/ruby/blob/trunk/array.c#L4271 return ST_CONTINUE; } +static void +rb_ary_union(VALUE ary_union, VALUE ary) +{ + long i; + for (i = 0; i < RARRAY_LEN(ary); i++) { + VALUE elt = rb_ary_elt(ary, i); + if (rb_ary_includes_by_eql(ary_union, elt)) continue; + rb_ary_push(ary_union, elt); + } +} + /* * call-seq: * ary | other_ary -> new_ary @@ -4295,16 +4306,8 @@ rb_ary_or(VALUE ary1, VALUE ary2) https://github.com/ruby/ruby/blob/trunk/array.c#L4306 ary2 = to_ary(ary2); if (RARRAY_LEN(ary1) + RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) { ary3 = rb_ary_new(); - for (i=0; i<RARRAY_LEN(ary1); i++) { - VALUE elt = rb_ary_elt(ary1, i); - if (rb_ary_includes_by_eql(ary3, elt)) continue; - rb_ary_push(ary3, elt); - } - for (i=0; i<RARRAY_LEN(ary2); i++) { - VALUE elt = rb_ary_elt(ary2, i); - if (rb_ary_includes_by_eql(ary3, elt)) continue; - rb_ary_push(ary3, elt); - } + rb_ary_union(ary3, ary1); + rb_ary_union(ary3, ary2); return ary3; } @@ -4353,21 +4356,9 @@ rb_ary_union_multi(int argc, VALUE *argv https://github.com/ruby/ruby/blob/trunk/array.c#L4356 if (sum <= SMALL_ARRAY_LEN) { ary_union = rb_ary_new(); - for (j = 0; j < RARRAY_LEN(ary); j++) { - VALUE elt = rb_ary_elt(ary, j); - if (rb_ary_includes_by_eql(ary_union, elt)) continue; - rb_ary_push(ary_union, elt); - } - - for (i = 0; i < argc; i++) { - VALUE argv_i = argv[i]; - - for (j = 0; j < RARRAY_LEN(argv_i); j++) { - VALUE elt = rb_ary_elt(argv_i, j); - if (rb_ary_includes_by_eql(ary_union, elt)) continue; - rb_ary_push(ary_union, elt); - } - } + rb_ary_union(ary_union, ary); + for (i = 0; i < argc; i++) rb_ary_union(ary_union, argv[i]); + return ary_union; } -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/