Permalink
Browse files

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

  • Loading branch information...
matz committed Nov 15, 2016
1 parent 739dad6 commit 92f72c749006407db4fa4a4faf123bde4a3043e4
Showing with 14 additions and 3 deletions.
  1. +14 −3 mrblib/string.rb
View
@@ -159,16 +159,27 @@ def []=(*args)
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 @@ def []=(*args)
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

0 comments on commit 92f72c7

Please sign in to comment.