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 <gemini@google.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2025-07-25 08:15:23 +09:00
parent 2250171071
commit 19b6cacbb5
+18 -25
View File
@@ -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: