make String#[]= to take Ranges as position argument

This commit is contained in:
Yukihiro "Matz" Matsumoto
2016-11-16 02:04:56 +09:00
parent 739dad6e87
commit 92f72c7490
+14 -3
View File
@@ -159,16 +159,27 @@ class String
anum = args.size
if anum == 2
pos, value = args
if pos.kind_of? String
case pos
when String
posnum = self.index(pos)
if posnum
b = self[0, posnum.to_i]
a = self[(posnum + pos.length)..-1]
self.replace([b, value, a].join(''))
return value
else
raise IndexError, "string not matched"
end
when Range
head = pos.begin
tail = pos.end
tail += self.length if tail < 0
if pos.exclude_end?
tail -= 1
end
if tail < 0 || tail > self.length
raise IndexError, "index #{args[0]} out of string"
end
return self[head, tail-head]=value
else
pos += self.length if pos < 0
if pos < 0 || pos > self.length
@@ -177,8 +188,8 @@ class String
b = self[0, pos.to_i]
a = self[pos + 1..-1]
self.replace([b, value, a].join(''))
return value
end
return value
elsif anum == 3
pos, len, value = args
pos += self.length if pos < 0