How to insert a string to another string in Ruby
The insert() method inserts a string into another string.
The insert() method takes two parameters:
- The first parameter is the index position where we insert the new string or sub-string.
- The second one is the sub-string to be inserted.
Syntax
str.insert(index, substr)
Parameters
str: This is the string where we want to insert a new string.
index: This is the index position to start the new string or sub-string insertion.
substr: This is the sub-string we want to insert to the str string.
Return value
The value returned is str but with substr inserted into it.
Note: If the index is negative, we count backward to start insertion.
Code example
# create some stringsstr1 = "Edpre"str2 = "s"str3 = "awme"# insert substringsr1 = str1.insert(5, "sso") # 6th positionr2 = str2.insert(0, "i") # 1st positionr3 = str3.insert(2, "eso") # 3rd position# print resultsputs r1puts r2puts r3
Explanation
-
Line 2 to 4: String variables
str1,str2andstr3are created and initialized. -
Line 7: We insert
"sso"to the6thindex position of stringstr1and store the result in the variable,r1. -
Line 8:
"i"is inserted tostr2at the first index position. The result is stored inside the variable,r2. -
Line 9:
"eso"is inserted to thestr3string at the third index position.