Merge pull request #3527 from ksss/string-gsub

Update String#gsub and String#gsub!
This commit is contained in:
Yukihiro "Matz" Matsumoto
2017-03-20 02:23:11 +09:00
committed by GitHub
2 changed files with 33 additions and 21 deletions
+28 -21
View File
@@ -58,28 +58,34 @@ class String
#
# ISO 15.2.10.5.18
def gsub(*args, &block)
if args.size == 2
pattern, replace = *args
plen = pattern.length
replace = replace.to_str
offset = 0
result = []
while found = index(pattern, offset)
result << self[offset, found - offset]
offset = found + plen
result << replace.__sub_replace(self[0, found], pattern, self[offset..-1] || "")
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"
return to_enum(:gsub, *args) if args.length == 1 && !block
raise ArgumentError, "wrong number of arguments" unless (1..2).include?(args.length)
pattern, replace = *args
plen = pattern.length
if args.length == 2 && block
block = nil
end
if !replace.nil? || !block
replace = replace.to_str
end
offset = 0
result = []
while found = index(pattern, offset)
result << self[offset, found - offset]
offset = found + plen
result << if block
block.call(pattern).to_s
else
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
end
##
@@ -91,6 +97,7 @@ class String
# ISO 15.2.10.5.19
def gsub!(*args, &block)
raise RuntimeError, "can't modify frozen String" if frozen?
return to_enum(:gsub!, *args) if args.length == 1 && !block
str = self.gsub(*args, &block)
return nil if str == self
self.replace(str)
+5
View File
@@ -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', '<\0><\1><\2>'))
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
assert('String#gsub with backslash') do