summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb19
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb9
-rw-r--r--src/vm.c14
3 files changed, 34 insertions, 8 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 78d9ff78a..49d0db0d5 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -490,4 +490,23 @@ class Array
self
end
end
+
+ ##
+ # call-seq:
+ # ary.insert(index, obj...) -> ary
+ #
+ # Inserts the given values before the element with the given +index+.
+ #
+ # Negative indices count backwards from the end of the array, where +-1+ is
+ # the last element.
+ #
+ # a = %w{ a b c d }
+ # a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
+ # a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
+
+ def insert(idx, *args)
+ idx += self.size + 1 if idx < 0
+ self[idx, 0] = args
+ self
+ end
end
diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb
index 0b425281f..d15ea2a64 100644
--- a/mrbgems/mruby-array-ext/test/array.rb
+++ b/mrbgems/mruby-array-ext/test/array.rb
@@ -197,3 +197,12 @@ assert("Array#reject!") do
assert_equal [1, 2, 3], a.reject! { |val| val > 3 }
assert_equal [1, 2, 3], a
end
+
+assert("Array#insert") do
+ a = ["a", "b", "c", "d"]
+ assert_equal ["a", "b", 99, "c", "d"], a.insert(2, 99)
+ assert_equal ["a", "b", 99, "c", 1, 2, 3, "d"], a.insert(-2, 1, 2, 3)
+
+ b = ["a", "b", "c", "d"]
+ assert_equal ["a", "b", "c", "d", nil, nil, 99], b.insert(6, 99)
+end
diff --git a/src/vm.c b/src/vm.c
index da8c62f51..8443c981c 100644
--- a/src/vm.c
+++ b/src/vm.c
@@ -992,12 +992,6 @@ RETRY_TRY_BLOCK:
ci->mid = mid;
ci->proc = m;
ci->stackent = mrb->c->stack;
- if (n == CALL_MAXARGS) {
- ci->argc = -1;
- }
- else {
- ci->argc = n;
- }
if (c->tt == MRB_TT_ICLASS) {
ci->target_class = c->c;
}
@@ -1013,9 +1007,11 @@ RETRY_TRY_BLOCK:
if (MRB_PROC_CFUNC_P(m)) {
if (n == CALL_MAXARGS) {
+ ci->argc = -1;
ci->nregs = 3;
}
else {
+ ci->argc = n;
ci->nregs = n + 2;
}
result = m->body.func(mrb, recv);
@@ -1044,11 +1040,13 @@ RETRY_TRY_BLOCK:
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
- if (ci->argc < 0) {
+ if (n == CALL_MAXARGS) {
+ ci->argc = -1;
stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs, 3);
}
else {
- stack_extend(mrb, irep->nregs, ci->argc+2);
+ ci->argc = n;
+ stack_extend(mrb, irep->nregs, n+2);
}
regs = mrb->c->stack;
pc = irep->iseq;