diff options
| author | ksss <[email protected]> | 2017-03-19 23:04:22 +0900 |
|---|---|---|
| committer | ksss <[email protected]> | 2017-03-19 23:04:22 +0900 |
| commit | 7a74a617ea8ba8deba22a22263f4188419d8d02d (patch) | |
| tree | 3aa3e5a95ec1d0be101536ad8db6c917388a0ff4 | |
| parent | 67a6982710f7538ef1f568fc9e87cfd3c50857c2 (diff) | |
| download | mruby-7a74a617ea8ba8deba22a22263f4188419d8d02d.tar.gz mruby-7a74a617ea8ba8deba22a22263f4188419d8d02d.zip | |
Callback should yield with pattern every time
| -rw-r--r-- | mrblib/string.rb | 43 | ||||
| -rw-r--r-- | test/t/string.rb | 5 |
2 files changed, 29 insertions, 19 deletions
diff --git a/mrblib/string.rb b/mrblib/string.rb index 24487cb00..26dbdcb9c 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -59,28 +59,33 @@ class String # ISO 15.2.10.5.18 def gsub(*args, &block) return to_enum(:gsub, *args) if args.length == 1 && !block - if args.size == 2 - pattern, replace = *args - plen = pattern.length + 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 - 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 + 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 - 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 + result << self[offset..-1] if offset < length + result.join end ## diff --git a/test/t/string.rb b/test/t/string.rb index ddc74fa54..c99457d7e 100644 --- a/test/t/string.rb +++ b/test/t/string.rb @@ -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 |
