Unverified Commit 7a74a617 authored by ksss's avatar ksss

Callback should yield with pattern every time

parent 67a69827
...@@ -59,28 +59,33 @@ class String ...@@ -59,28 +59,33 @@ class String
# ISO 15.2.10.5.18 # ISO 15.2.10.5.18
def gsub(*args, &block) def gsub(*args, &block)
return to_enum(:gsub, *args) if args.length == 1 && !block return to_enum(:gsub, *args) if args.length == 1 && !block
if args.size == 2 raise ArgumentError, "wrong number of arguments" unless (1..2).include?(args.length)
pattern, replace = *args
plen = pattern.length pattern, replace = *args
plen = pattern.length
if args.length == 2 && block
block = nil
end
if !replace.nil? || !block
replace = replace.to_str replace = replace.to_str
offset = 0 end
result = [] offset = 0
while found = index(pattern, offset) result = []
result << self[offset, found - offset] while found = index(pattern, offset)
offset = found + plen result << self[offset, found - offset]
result << replace.__sub_replace(self[0, found], pattern, self[offset..-1] || "") offset = found + plen
if plen == 0 result << if block
result << self[offset, 1] block.call(pattern).to_s
offset += 1 else
end replace.__sub_replace(self[0, found], pattern, self[offset..-1] || "")
end
if plen == 0
result << self[offset, 1]
offset += 1
end end
result << self[offset..-1] if offset < length
result.join
elsif args.size == 1 && block
split(args[0], -1).join(block.call(args[0]))
else
raise ArgumentError, "wrong number of arguments"
end end
result << self[offset..-1] if offset < length
result.join
end end
## ##
......
...@@ -373,6 +373,11 @@ assert('String#gsub', '15.2.10.5.18') do ...@@ -373,6 +373,11 @@ assert('String#gsub', '15.2.10.5.18') do
assert_equal('A', 'a'.gsub('a'){|w| w.capitalize }) assert_equal('A', 'a'.gsub('a'){|w| w.capitalize })
assert_equal("<a><><>", 'a'.gsub('a', '<\0><\1><\2>')) assert_equal("<a><><>", 'a'.gsub('a', '<\0><\1><\2>'))
assert_equal(".h.e.l.l.o.", "hello".gsub("", ".")) assert_equal(".h.e.l.l.o.", "hello".gsub("", "."))
a = []
assert_equal(".h.e.l.l.o.", "hello".gsub("") { |i| a << i; "." })
assert_equal(["", "", "", "", "", ""], a)
assert_raise(ArgumentError) { "".gsub }
assert_raise(ArgumentError) { "".gsub("", "", "") }
end end
assert('String#gsub with backslash') do assert('String#gsub with backslash') 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