What is the prepend() method of a string in Ruby?

Overview

In Ruby, we can use the prepend() method to prepend one string or multiple strings to another string. When we prepend a certain string to another using the prepend method, we get a new string with the latter concatenated with the former.

Syntax

str.prepend(other_str)

Where str is the string we want to prepend the other string to.

Parameter

other_str: This is a mandatory parameter. It is the string we want to prepend to str.

Return value

The value returned is the new string, which is composed of the other_str prepended to str.

Code example

# create strings
str1 = "dear"
str2 = "Edpresso"
# prepend strings
a = str1.prepend("hi")
b = str2.prepend("Welcome to ")
# print results
puts a
puts b

Explanation

  • Lines 2-3: We create some strings to which we want to prepend other strings.

  • Lines 6-7: We prepend "hi" to str1 and "welcome to " to str2. We do this by using the prepend() method.

  • Lines 10-11: We print our results to the console using the puts method.

Free Resources