summaryrefslogtreecommitdiffhomepage
path: root/mrbgems
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-04-21 22:14:04 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-04-23 00:22:24 +0900
commita48e0018fd8065d23f67fe354226ca346728ee87 (patch)
tree6ee9d4716b30b0d74ecbb02a22095122e391c749 /mrbgems
parent951f027b1274bb2e5ea7e5b943c9af21b4fc89d5 (diff)
downloadmruby-a48e0018fd8065d23f67fe354226ca346728ee87.tar.gz
mruby-a48e0018fd8065d23f67fe354226ca346728ee87.zip
Add Array#insert
Diffstat (limited to 'mrbgems')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb27
-rw-r--r--mrbgems/mruby-array-ext/test/array.rb9
2 files changed, 36 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 78d9ff78a..df7635e8f 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -490,4 +490,31 @@ 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, *obj)
+ idx += self.size + 1 if idx < 0
+ ary = []
+ before_ary = self[0, idx]
+ after_ary = self[idx, self.size]
+ before_ary.each {|val| ary << val} unless before_ary == nil
+ while ary.size < idx
+ ary << nil
+ end
+ obj.each {|val| ary << val} unless obj == nil
+ after_ary.each {|val| ary << val} unless after_ary == nil
+ self.replace(ary)
+ 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