Inserting A String Into A String
by Kyle on
Inserts other_str before the character given at the index, modifying the string. Negative indices count from the end of the string, and insert after the given character. The intent is to insert a string so that it starts at the given index.
"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"
You could also do this:
"abcd".sub(/^.{2}/,'\0X') #=> abXcd