Merge pull request #2669 from suzukaze/string.insert

Add String#insert
This commit is contained in:
Yukihiro "Matz" Matsumoto
2014-12-13 15:40:37 +09:00
2 changed files with 37 additions and 0 deletions
+27
View File
@@ -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
+10
View File
@@ -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