String#replace
str.replace(other_str) -> str The replace method replaces the entire contents of a string with the contents of another value. Unlike methods like gsub or sub that search for patterns, replace discards everything in the string and substitutes it with the new value entirely.
This method is particularly useful when you want to reuse a single String object rather than creating a new one, which can be important in performance-critical code or when you need to maintain object identity. Since strings in Ruby are mutable, replace lets you change the contents without allocating a new object on the heap.
That makes it a good fit for buffers, accumulators, and objects that are shared by reference. If other code is holding onto the same underlying object, replace updates what they see without swapping out the object itself. That is a different tradeoff from assignment, which simply points a variable at a new string.
It is the right choice when the identity of the object matters more than the current contents. That comes up in reusable builders, cache refreshes, and helper methods that need to update a buffer without changing which object is being reused.
Syntax
str.replace(other_str)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
other_str | String | — | The string to replace the contents with |
A single required argument keeps the method simple. Pass in any string, and replace will copy its content byte-for-byte into the receiver. The return value is the receiver itself, so you can chain further calls or capture the result without storing the original reference separately.
Examples
Basic usage
greeting = "Hello"
greeting.replace("Goodbye")
puts greeting
# => Goodbye
The length of the new value does not matter to replace. Passing an empty string clears the contents completely while keeping the same object alive. This is useful in reset scenarios where other parts of the program hold a reference to the string and should see the cleared value.
Replacing with an empty string
text = "Some content"
text.replace("")
puts text.empty?
# => true
Emptying a buffer with replace("") is a common pattern when the same object needs to cycle through many values without creating new allocations. After the call, the value is zero-length but still the same object, so any code holding a reference to it will see the cleared content immediately.
Common Patterns
Resetting a string buffer
buffer = String.new
buffer.replace("First content")
buffer.replace("Second content")
puts buffer
# => Second content
Buffers benefit from replace when the object identity matters more than the current value. If another part of the program holds a reference to the buffer, reassigning the variable to a new string would leave that reference pointing at stale content. Using replace updates all views of it at once.
Using replace instead of reassignment
When you need to modify a string in place without creating a new object:
def process_input!(string)
string.replace(string.strip.upcase)
end
data = " hello world "
process_input!(data)
puts data
# => HELLO WORLD
The method is deliberate intentional, not magical. Use it when object identity matters, and prefer a normal assignment when the caller only cares about the value. That keeps the code easier to follow and makes the mutation boundary obvious to the next person reading it.
This distinction is especially important in method arguments. When a string is passed into a method and the method calls replace on it, the caller sees the updated content without any return value or reassignment. That is a powerful pattern, but it is also one that benefits from a clear name like process_input! to signal the mutation. If the contract is not obvious, a regular assignment with a return value is usually the safer choice.
The same principle applies when working with frozen strings:
template = "Hello, NAME".freeze
# template.replace("Hi") # => FrozenError (can't modify frozen String)
replace requires a mutable receiver, so frozen strings will raise FrozenError.