String#replace
str.replace(other_str) -> str Returns:
String · Updated March 13, 2026 · String Methods strings mutation in-place
The replace method replaces the entire contents of a string with the contents of another string. 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 the same 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.
Syntax
str.replace(other_str)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
other_str | String | — | The string to replace the contents with |
Examples
Basic usage
greeting = "Hello"
greeting.replace("Goodbye")
puts greeting
# => Goodbye
Replacing with an empty string
text = "Some content"
text.replace("")
puts text.empty?
# => true
Common Patterns
Resetting a string buffer
buffer = String.new
buffer.replace("First content")
buffer.replace("Second content")
puts buffer
# => Second content
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