From 6eb02a892dbd0f0631c0362805fa995194290611 Mon Sep 17 00:00:00 2001 From: ksss Date: Wed, 15 Mar 2017 16:48:47 +0900 Subject: Use duplicated object for block args --- mrblib/string.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mrblib/string.rb b/mrblib/string.rb index 7add360a8..5510bf6de 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -11,11 +11,12 @@ class String # ISO 15.2.10.5.15 def each_line(&block) offset = 0 - while pos = self.index("\n", offset) - block.call(self[offset, pos + 1 - offset]) + this = dup + while pos = this.index("\n", offset) + block.call(this[offset, pos + 1 - offset]) offset = pos + 1 end - block.call(self[offset, self.size - offset]) if self.size > offset + block.call(this[offset, this.size - offset]) if this.size > offset self end -- cgit v1.2.3 From 673ce237c48ed6cd3c516ae6e03835e7b41e278f Mon Sep 17 00:00:00 2001 From: ksss Date: Wed, 15 Mar 2017 16:50:27 +0900 Subject: Suuport custom separator --- mrblib/string.rb | 11 +++++++---- test/t/string.rb | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/mrblib/string.rb b/mrblib/string.rb index 5510bf6de..f3890dfa7 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -9,12 +9,15 @@ class String # and pass the respective line. # # ISO 15.2.10.5.15 - def each_line(&block) + def each_line(rs = "\n", &block) + return block.call(self) if rs.nil? + rs = rs.to_str offset = 0 + rs_len = rs.length this = dup - while pos = this.index("\n", offset) - block.call(this[offset, pos + 1 - offset]) - offset = pos + 1 + while pos = this.index(rs, offset) + block.call(this[offset, pos + rs_len - offset]) + offset = pos + rs_len end block.call(this[offset, this.size - offset]) if this.size > offset self diff --git a/test/t/string.rb b/test/t/string.rb index 25c599ad4..ddc74fa54 100644 --- a/test/t/string.rb +++ b/test/t/string.rb @@ -341,6 +341,12 @@ assert('String#each_line', '15.2.10.5.15') do end assert_equal list, n_list + + n_list.clear + a.each_line("li") do |line| + n_list << line + end + assert_equal ["first li", "ne\nsecond li", "ne\nthird li", "ne"], n_list end assert('String#empty?', '15.2.10.5.16') do -- cgit v1.2.3 From 4ee79a877728f07c2017ba0a225bf9647bfca22a Mon Sep 17 00:00:00 2001 From: ksss Date: Wed, 15 Mar 2017 16:51:04 +0900 Subject: Support to return enumerator when no block given --- mrblib/string.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/mrblib/string.rb b/mrblib/string.rb index f3890dfa7..6e55ee341 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -10,6 +10,7 @@ class String # # ISO 15.2.10.5.15 def each_line(rs = "\n", &block) + return to_enum(:each_line, rs, &block) unless block return block.call(self) if rs.nil? rs = rs.to_str offset = 0 -- cgit v1.2.3