String insert, delete Examples
This page was last reviewed on Aug 14, 2021.
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.
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 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 lowercase "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
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).
© 2007-2024 Sam Allen.