Insert example. We can use the insert() method to place a substring inside an existing string. The original string is modified—no assignment is needed.
Detail With an invalid index, the insert() method will throw an IndexError. We may need to check against the string's length.
Detail With a negative index, the insertion is based on the last index. If we pass -1, the insertion occurs before the last character.
# Input string.
value = "socrates"# Insert string into the input string.
value.insert(3, "k-")
puts value
# Now prepend two characters.
value.insert(0, "??")
puts valuesock-rates
??sock-rates
Delete. This method deletes individual characters, not entire substrings. So if we pass 2 chars like "et" to it, all the lowercase "e" and "t" chars are erased.
Remove substring. To remove or delete an entire substring from a string, we can invoke the sub() method. Here we replace the substring "country" with an empty string—this removes it.
value = "old country home"
puts value
# Remove substring from string.
value.sub!("country ", "")
puts valueold country home
old home
A summary. We used insert and delete. It is important to understand that we can use the sub() method to remove substrings. We replace a substring with an empty string literal.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 14, 2021 (image).