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.
Note With an invalid index, the insert() method will throw an IndexError. We may need to check against the string's length.
Note 2 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 uppercase "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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.