Insert
, deleteIn 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
exampleWe can use the insert()
method to place a substring inside an existing string
. The original string
is modified—no assignment is needed.
insert()
method will throw an IndexError
. We may need to check against the string
's length.# 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.
animal = "ELEPHANT" puts animal # Delete these 2 characters. animal.delete!("ET") puts animalELEPHANT LPHAN
Remove
substringTo 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
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.