String#chomp!
string.chomp! -> self or nil
string.chomp!(separator) -> self or nil Returns:
String or nil · Updated March 13, 2026 · Core Classes string chomp newline mutation bang-method
The chomp! method is the mutating (in-place) version of chomp. It’s part of Ruby’s String class and is commonly used to remove trailing record separators—typically newlines—from strings.
Syntax
string.chomp! # Uses the default record separator ($/)
string.chomp!(separator) # Uses the specified separator
Parameters
separator(optional) — A string to use as the record separator. Defaults to$/(usually"\n").
How It Works
chomp! removes the record separator from the end of the string only if it exists. The key characteristic of bang methods (methods ending with !) is that they modify the object in place rather than returning a new string.
The Bang Convention
In Ruby, bang methods (suffix !) conventionally indicate mutation. Unlike their non-bang counterparts, bang methods modify the receiver directly:
chomp— Returns a new string (non-mutating)chomp!— Modifies the string in place (mutating)
Return Value
- Returns
selfif a separator was found and removed - Returns
nilif no separator was present at the end
This nil return is a hallmark of bang methods in Ruby and serves as an indicator that no modification occurred.
Examples
Example 1: Removing a trailing newline
greeting = "Hello, World!\n"
greeting.chomp!
puts greeting.inspect # => "Hello, World!"
Example 2: Handling multiple separators
# Multiple newlines are NOT removed - only ONE separator
text = "line1\n\n\n"
text.chomp!
puts text.inspect # => "line1\n\n"
# Using a custom separator
data = "record1|record2|record3|"
data.chomp!("|")
puts data.inspect # => "record1|record2|record3"
Example 3: Checking for nil return
# When no separator exists, chomp! returns nil
message = "No newline here"
result = message.chomp!
puts result.nil? # => true
puts message # => "No newline here" (unchanged)
# Common pattern: conditional processing
if message.chomp!
puts "Newline removed"
else
puts "No newline to remove"
end
Comparison: chomp vs chomp!
# chomp - creates a new string
original = "text\n"
copy = original.chomp
original # => "text\n" (unchanged)
copy # => "text" (new string)
# chomp! - modifies in place
original = "text\n"
original.chomp!
original # => "text" (modified!)
Common Use Cases
- Reading file lines — Removing newlines after
gets - Processing user input — Cleaning trailing whitespace
- String parsing — Stripping record delimiters