summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-string-ext
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-12-13 15:40:37 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-12-13 15:40:37 +0900
commit05e6513fb4422bf2b2ef8861ea895ce9b68d03e6 (patch)
tree1551bd98d27882782431a8baf02e963cc7506ee7 /mrbgems/mruby-string-ext
parentf1481105b74909335c89b8db3a705a0eee6e42e3 (diff)
parent45a442a9d7ee835de7ab8b205e9c7bb2be3b82f5 (diff)
downloadmruby-05e6513fb4422bf2b2ef8861ea895ce9b68d03e6.tar.gz
mruby-05e6513fb4422bf2b2ef8861ea895ce9b68d03e6.zip
Merge pull request #2669 from suzukaze/string.insert
Add String#insert
Diffstat (limited to 'mrbgems/mruby-string-ext')
-rw-r--r--mrbgems/mruby-string-ext/mrblib/string.rb27
-rw-r--r--mrbgems/mruby-string-ext/test/string.rb10
2 files changed, 37 insertions, 0 deletions
diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb
index 34744cc38..88bdd9090 100644
--- a/mrbgems/mruby-string-ext/mrblib/string.rb
+++ b/mrbgems/mruby-string-ext/mrblib/string.rb
@@ -217,4 +217,31 @@ class String
end
str
end
+
+ ##
+ # call-seq:
+ # str.insert(index, other_str) -> str
+ #
+ # Inserts <i>other_str</i> before the character at the given
+ # <i>index</i>, modifying <i>str</i>. Negative indices count from the
+ # end of the string, and insert <em>after</em> the given character.
+ # The intent is insert <i>aString</i> so that it starts at the given
+ # <i>index</i>.
+ #
+ # "abcd".insert(0, 'X') #=> "Xabcd"
+ # "abcd".insert(3, 'X') #=> "abcXd"
+ # "abcd".insert(4, 'X') #=> "abcdX"
+ # "abcd".insert(-3, 'X') #=> "abXcd"
+ # "abcd".insert(-1, 'X') #=> "abcdX"
+ #
+ def insert(idx, str)
+ pos = idx.to_i
+ pos += self.size + 1 if pos < 0
+
+ raise IndexError, "index #{idx.to_i} out of string" if pos < 0 || pos > self.size
+
+ return self + str if pos == -1
+ return str + self if pos == 0
+ return self[0..pos - 1] + str + self[pos..-1]
+ end
end
diff --git a/mrbgems/mruby-string-ext/test/string.rb b/mrbgems/mruby-string-ext/test/string.rb
index eba666e13..940ffb351 100644
--- a/mrbgems/mruby-string-ext/test/string.rb
+++ b/mrbgems/mruby-string-ext/test/string.rb
@@ -370,3 +370,13 @@ assert('String#next') do
a = "00"; a.next!
assert_equal "01", a
end
+
+assert('String#insert') do
+ assert_equal "Xabcd", "abcd".insert(0, 'X')
+ assert_equal "abcXd", "abcd".insert(3, 'X')
+ assert_equal "abcdX", "abcd".insert(4, 'X')
+ assert_equal "abXcd", "abcd".insert(-3, 'X')
+ assert_equal "abcdX", "abcd".insert(-1, 'X')
+ assert_raise(IndexError) { "abcd".insert(5, 'X') }
+ assert_raise(IndexError) { "abcd".insert(-6, 'X') }
+end