diff options
| author | takahashim <[email protected]> | 2015-09-16 18:50:03 +0900 |
|---|---|---|
| committer | takahashim <[email protected]> | 2015-09-16 18:50:03 +0900 |
| commit | f1c23a0f75a4a38c5077e1df30af200f3700752f (patch) | |
| tree | e6e296d99ad3780e769a5bae0d71bb5a6de75c9a /mrblib | |
| parent | 08f9a3ed041c2461fb9264c7beb64ed16a8df4e9 (diff) | |
| download | mruby-f1c23a0f75a4a38c5077e1df30af200f3700752f.tar.gz mruby-f1c23a0f75a4a38c5077e1df30af200f3700752f.zip | |
support String#[]= with 3 args
Diffstat (limited to 'mrblib')
| -rw-r--r-- | mrblib/string.rb | 49 |
1 files changed, 42 insertions, 7 deletions
diff --git a/mrblib/string.rb b/mrblib/string.rb index 05b13cb43..5765cff9b 100644 --- a/mrblib/string.rb +++ b/mrblib/string.rb @@ -154,13 +154,48 @@ class String end ## - # Modify +self+ by replacing the content of +self+ - # at the position +pos+ with +value+. - def []=(pos, value) - pos += self.length if pos < 0 - b = self[0, pos] - a = self[pos + 1..-1] - self.replace([b, value, a].join('')) + # Modify +self+ by replacing the content of +self+. + # The portion of the string affected is determined using the same criteria as +String#[]+. + def []=(*args) + anum = args.size + if anum == 2 + pos, value = args + if pos.kind_of? 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 + else + pos += self.length if pos < 0 + if pos < 0 || pos > self.length + raise IndexError, "index #{args[0]} out of string" + end + b = self[0, pos.to_i] + a = self[pos + 1..-1] + self.replace([b, value, a].join('')) + return value + end + elsif anum == 3 + pos, len, value = args + pos += self.length if pos < 0 + if pos < 0 || pos > self.length + raise IndexError, "index #{args[0]} out of string" + end + if len < 0 + raise IndexError, "negative length #{len}" + end + b = self[0, pos.to_i] + a = self[pos + len..-1] + self.replace([b, value, a].join('')) + return value + else + raise ArgumentError, "wrong number of arguments (#{anum} for 2..3)" + end end ## |
