summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib/array.rb
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/mruby-array-ext/mrblib/array.rb
parent951f027b1274bb2e5ea7e5b943c9af21b4fc89d5 (diff)
downloadmruby-a48e0018fd8065d23f67fe354226ca346728ee87.tar.gz
mruby-a48e0018fd8065d23f67fe354226ca346728ee87.zip
Add Array#insert
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb27
1 files changed, 27 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