From 19b6cacbb53a84fdeb468a762d042493fcf65f6e Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Fri, 25 Jul 2025 08:15:23 +0900 Subject: [PATCH] mruby-array-ext: refactor ary_compact to use ary_compact_bang This removes code duplication by making ary_compact call ary_compact_bang on a duplicated array, centralizing the compaction logic. It also reorders the functions to remove the need for a forward declaration. Co-authored-by: Gemini --- mrbgems/mruby-array-ext/src/array.c | 43 ++++++++++++----------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/mrbgems/mruby-array-ext/src/array.c b/mrbgems/mruby-array-ext/src/array.c index 0f28b7498..ef716b52e 100644 --- a/mrbgems/mruby-array-ext/src/array.c +++ b/mrbgems/mruby-array-ext/src/array.c @@ -191,31 +191,6 @@ ary_slice_bang(mrb_state *mrb, mrb_value self) return ary; } -/* - * call-seq: - * ary.compact -> new_ary - * - * Returns a copy of `self` with all `nil` elements removed. - * - * [ "a", nil, "b", nil, "c", nil ].compact - * #=> [ "a", "b", "c" ] - */ - -static mrb_value -ary_compact(mrb_state *mrb, mrb_value self) -{ - mrb_value ary = mrb_ary_new(mrb); - mrb_int len = RARRAY_LEN(self); - - for (mrb_int i = 0; i < len; i++) { - mrb_value v = RARRAY_PTR(self)[i]; - if (!mrb_nil_p(v)) { - mrb_ary_push(mrb, ary, v); - } - } - return ary; -} - /* * call-seq: * ary.compact! -> ary or nil @@ -247,6 +222,24 @@ ary_compact_bang(mrb_state *mrb, mrb_value self) return self; } +/* + * call-seq: + * ary.compact -> new_ary + * + * Returns a copy of `self` with all `nil` elements removed. + * + * [ "a", nil, "b", nil, "c", nil ].compact + * #=> [ "a", "b", "c" ] + */ + +static mrb_value +ary_compact(mrb_state *mrb, mrb_value self) +{ + mrb_value ary = mrb_ary_dup(mrb, self); + ary_compact_bang(mrb, ary); + return ary; +} + /* * call-seq: