Commit f1c23a0f authored by takahashim's avatar takahashim

support String#[]= with 3 args

parent 08f9a3ed
...@@ -154,13 +154,48 @@ class String ...@@ -154,13 +154,48 @@ class String
end end
## ##
# Modify +self+ by replacing the content of +self+ # Modify +self+ by replacing the content of +self+.
# at the position +pos+ with +value+. # The portion of the string affected is determined using the same criteria as +String#[]+.
def []=(pos, value) def []=(*args)
pos += self.length if pos < 0 anum = args.size
b = self[0, pos] if anum == 2
a = self[pos + 1..-1] pos, value = args
self.replace([b, value, a].join('')) if pos.kind_of? 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
else
pos += self.length if pos < 0
if pos < 0 || pos > self.length
raise IndexError, "index #{args[0]} out of string"
end
b = self[0, pos.to_i]
a = self[pos + 1..-1]
self.replace([b, value, a].join(''))
return value
end
elsif anum == 3
pos, len, value = args
pos += self.length if pos < 0
if pos < 0 || pos > self.length
raise IndexError, "index #{args[0]} out of string"
end
if len < 0
raise IndexError, "negative length #{len}"
end
b = self[0, pos.to_i]
a = self[pos + len..-1]
self.replace([b, value, a].join(''))
return value
else
raise ArgumentError, "wrong number of arguments (#{anum} for 2..3)"
end
end end
## ##
......
...@@ -122,6 +122,69 @@ assert('String#[] with Range') do ...@@ -122,6 +122,69 @@ assert('String#[] with Range') do
assert_equal 'bc', j2 assert_equal 'bc', j2
end end
assert('String#[]=') do
# length of args is 1
a = 'abc'
a[0] = 'X'
assert_equal 'Xbc', a
b = 'abc'
b[-1] = 'X'
assert_equal 'abX', b
c = 'abc'
assert_raise(IndexError) do
c[10] = 'X'
end
d = 'abc'
assert_raise(IndexError) do
d[-10] = 'X'
end
e = 'abc'
e[1.1] = 'X'
assert_equal 'aXc', e
# length of args is 2
a1 = 'abc'
assert_raise(IndexError) do
a1[0, -1] = 'X'
end
b1 = 'abc'
assert_raise(IndexError) do
b1[10, 0] = 'X'
end
c1 = 'abc'
assert_raise(IndexError) do
c1[-10, 0] = 'X'
end
d1 = 'abc'
d1[0, 0] = 'X'
assert_equal 'Xabc', d1
e1 = 'abc'
e1[1, 3] = 'X'
assert_equal 'aX', e1
# args is RegExp
# It will be tested in mrbgems.
# args is String
a3 = 'abc'
a3['bc'] = 'X'
assert_equal a3, 'aX'
b3 = 'abc'
assert_raise(IndexError) do
b3['XX'] = 'Y'
end
end
assert('String#capitalize', '15.2.10.5.7') do assert('String#capitalize', '15.2.10.5.7') do
a = 'abc' a = 'abc'
a.capitalize a.capitalize
......
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