From 45a442a9d7ee835de7ab8b205e9c7bb2be3b82f5 Mon Sep 17 00:00:00 2001 From: Jun Hiroe Date: Sat, 13 Dec 2014 14:48:37 +0900 Subject: Add String#insert --- mrbgems/mruby-string-ext/mrblib/string.rb | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'mrbgems/mruby-string-ext/mrblib/string.rb') 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 other_str before the character at the given + # index, modifying str. Negative indices count from the + # end of the string, and insert after the given character. + # The intent is insert aString so that it starts at the given + # index. + # + # "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 -- cgit v1.2.3