Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
ruby
insert
communitycreator

How to insert a string to another string in Ruby

okwudili onyejiaku

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 strings
str1 = "Edpre"
str2 = "s"
str3 = "awme"

# insert substrings
r1 = str1.insert(5, "sso")  # 6th position
r2 = str2.insert(0, "i")    # 1st position
r3 = str3.insert(2, "eso") # 3rd position

# print results
puts r1
puts r2
puts r3
Insert a string to another string in Ruby

Explanation

  • Line 2 to 4: String variables str1, str2 and str3 are created and initialized.

  • Line 7: We insert "sso" to the 6th index position of string str1 and store the result in the variable, r1.

  • Line 8: "i" is inserted to str2 at the first index position. The result is stored inside the variable, r2.

  • Line 9: "eso" is inserted to the str3 string at the third index position.

RELATED TAGS

string
ruby
insert
communitycreator
RELATED COURSES

View all Courses

Keep Exploring