Commit 97283faa authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto Committed by GitHub

Merge pull request #3176 from ksss/string-insert

String#insert should be destructive
parents 72b28f1e d83d9cd1
......@@ -254,14 +254,13 @@ class String
# "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]
if idx == -1
return self << str
elsif idx < 0
idx += 1
end
self[idx, 0] = str
self
end
##
......
......@@ -406,6 +406,10 @@ assert('String#insert') do
assert_equal "abcdX", "abcd".insert(-1, 'X')
assert_raise(IndexError) { "abcd".insert(5, 'X') }
assert_raise(IndexError) { "abcd".insert(-6, 'X') }
a = "abcd"
a.insert(0, 'X')
assert_equal "Xabcd", a
end
assert('String#prepend') do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment