From 92f72c749006407db4fa4a4faf123bde4a3043e4 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 16 Nov 2016 02:04:56 +0900 Subject: make String#[]= to take Ranges as position argument --- mrblib/string.rb | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'mrblib/string.rb') diff --git a/mrblib/string.rb b/mrblib/string.rb index 37441ec98..f22071b36 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -159,16 +159,27 @@ class String anum = args.size if anum == 2 pos, value = args - if pos.kind_of? String + case pos + when 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 + when Range + head = pos.begin + tail = pos.end + tail += self.length if tail < 0 + if pos.exclude_end? + tail -= 1 + end + if tail < 0 || tail > self.length + raise IndexError, "index #{args[0]} out of string" + end + return self[head, tail-head]=value else pos += self.length if pos < 0 if pos < 0 || pos > self.length @@ -177,8 +188,8 @@ class String b = self[0, pos.to_i] a = self[pos + 1..-1] self.replace([b, value, a].join('')) - return value end + return value elsif anum == 3 pos, len, value = args pos += self.length if pos < 0 -- cgit v1.2.3 From 1685eff2a5e672173d67916a1c96648df92b7271 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 16 Nov 2016 10:16:14 +0900 Subject: Fixed off-by-one error in String#[]= with Ranges --- mrblib/string.rb | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) (limited to 'mrblib/string.rb') diff --git a/mrblib/string.rb b/mrblib/string.rb index f22071b36..aa2ca9973 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -173,11 +173,8 @@ class String head = pos.begin tail = pos.end tail += self.length if tail < 0 - if pos.exclude_end? - tail -= 1 - end - if tail < 0 || tail > self.length - raise IndexError, "index #{args[0]} out of string" + unless pos.exclude_end? + tail += 1 end return self[head, tail-head]=value else -- cgit v1.2.3