String#prepend

Updated March 23, 2026 · String Methods
ruby string string-methods mutation

Overview

String#prepend adds the given string or strings to the beginning of the target string. Unlike string concatenation methods that produce a new string, prepend mutates the receiver. The method returns self — the modified string, not a new one.

Signature

prepend(*other_strings) -> str

Parameters:

  • *other_strings — One or more string arguments to prepend. Each argument must be a string. Numeric arguments are not accepted and will raise an ArgumentError.

Return value: The modified string (the same object as self).

Basic Usage

str = "world"
str.prepend("hello ")
# => "hello world"

Note that prepend modifies the original string:

str = "world"
str.prepend("hello ")
str
# => "hello world"

Calling prepend without arguments raises an error:

str = "world"
str.prepend
# => ArgumentError: wrong number of arguments (given 0, expected 1)

Prepending an Empty String

Prepending an empty string leaves the original unchanged:

str = "hello"
str.prepend("")
# => "hello"

Multiple Arguments (Ruby 2.4+)

Ruby 2.4 introduced the ability to pass multiple arguments to prepend. Each argument is prepended in order, so the first argument appears closest to the original string content, and the last argument appears at the very beginning.

str = "end"
str.prepend("middle ", "start ")
# => "start middle end"

Comparison with the + Operator

The + operator creates and returns a new string, leaving the original unchanged:

original = "world"
result = original + " hello"
# original is still "world"
# result is "world hello"

In contrast, prepend alters the original:

original = "world"
original.prepend("hello ")
# original is now "hello world"
# returns "hello world"

Choose prepend when you want to modify an existing string without creating intermediate objects. Use + when you prefer immutable semantics or need to preserve the original string.

Comparison with insert

String#insert offers another way to prepend content:

str = "world"
str.insert(0, "hello ")
# => "hello world"

Use insert(0, ...) when you need position flexibility, or prepend for straightforward prepending.

Integer Arguments

prepend does not accept integers, unlike concat, which accepts integers as a workaround (treating them as ASCII character codes).

"str".prepend(65)
# => ArgumentError: no implicit conversion of Integer into String

"str".concat(65)
# => "Astr"  (65 is ASCII for 'A')

Frozen String Error

Calling prepend on a frozen string raises a TypeError:

str = "hello".freeze
str.prepend("world ")
# => TypeError: can't modify frozen string: "hello"

This behavior is consistent with other mutating methods in Ruby. Always check frozen? before attempting mutation if the string may be frozen.

See Also

  • String#concat — concatenates strings at the end of a string; accepts integers as arguments
  • String#replace — replaces the entire contents of a string in place