Home
Ruby
String insert, delete Examples
Updated Mar 9, 2025
Dot Net Perls
Insert, delete. In Ruby, one string can be inserted into another. We use the insert() method and specify the index where to insert.
For insert, the original string is modified. Delete() just removes characters—to remove entire substrings, we use sub() and related methods.
sub
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 value
sock-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.
animal = "ELEPHANT" puts animal # Delete these 2 characters. animal.delete!("ET") puts animal
ELEPHANT LPHAN
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 value
old 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.
This page was last updated on Mar 9, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen