diff options
Diffstat (limited to 'mrbgems/mruby-string-ext')
| -rw-r--r-- | mrbgems/mruby-string-ext/mrblib/string.rb | 27 | ||||
| -rw-r--r-- | mrbgems/mruby-string-ext/test/string.rb | 10 |
2 files changed, 37 insertions, 0 deletions
diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb index 34744cc38..88bdd9090 100644 --- a/mrbgems/mruby-string-ext/mrblib/string.rb +++ b/mrbgems/mruby-string-ext/mrblib/string.rb @@ -217,4 +217,31 @@ class String end str end + + ## + # call-seq: + # str.insert(index, other_str) -> str + # + # Inserts <i>other_str</i> before the character at the given + # <i>index</i>, modifying <i>str</i>. Negative indices count from the + # end of the string, and insert <em>after</em> the given character. + # The intent is insert <i>aString</i> so that it starts at the given + # <i>index</i>. + # + # "abcd".insert(0, 'X') #=> "Xabcd" + # "abcd".insert(3, 'X') #=> "abcXd" + # "abcd".insert(4, 'X') #=> "abcdX" + # "abcd".insert(-3, 'X') #=> "abXcd" + # "abcd".insert(-1, 'X') #=> "abcdX" + # + def insert(idx, str) + pos = idx.to_i + pos += self.size + 1 if pos < 0 + + raise IndexError, "index #{idx.to_i} out of string" if pos < 0 || pos > self.size + + return self + str if pos == -1 + return str + self if pos == 0 + return self[0..pos - 1] + str + self[pos..-1] + end end diff --git a/mrbgems/mruby-string-ext/test/string.rb b/mrbgems/mruby-string-ext/test/string.rb index eba666e13..940ffb351 100644 --- a/mrbgems/mruby-string-ext/test/string.rb +++ b/mrbgems/mruby-string-ext/test/string.rb @@ -370,3 +370,13 @@ assert('String#next') do a = "00"; a.next! assert_equal "01", a end + +assert('String#insert') do + assert_equal "Xabcd", "abcd".insert(0, 'X') + assert_equal "abcXd", "abcd".insert(3, 'X') + assert_equal "abcdX", "abcd".insert(4, 'X') + assert_equal "abXcd", "abcd".insert(-3, 'X') + assert_equal "abcdX", "abcd".insert(-1, 'X') + assert_raise(IndexError) { "abcd".insert(5, 'X') } + assert_raise(IndexError) { "abcd".insert(-6, 'X') } +end |
