String#chomp
str.chomp(separator) String · Updated March 14, 2026 · String Methods The chomp method removes the trailing record separator from a string. By default, it removes \n, \r\n, or \r depending on the platform. This is particularly useful when reading lines from files or user input, where you typically want to remove the trailing newline.
Basic Usage
When called without arguments, chomp removes any trailing newline characters:
"hello\n".chomp
# => "hello"
"hello\r\n".chomp
# => "hello"
"hello\r".chomp
# => "hello"
If there’s no trailing separator, chomp returns the string unchanged:
"hello".chomp
# => "hello"
Specifying a Custom Separator
You can pass a string argument to remove a custom trailing separator:
"hello!".chomp("!")
# => "hello"
"path/to/file/".chomp("/")
# => "path/to/file"
"data---".chomp("---")
# => "data"
Using a Regex Separator
A regular expression can be used to remove more complex trailing patterns:
"hello123".chomp(/\d+/)
# => "hello"
"foo.bar.baz".chomp(/\.[a-z]+/)
# => "foo.bar"
Multiple Separators
If the separator appears multiple times at the end, chomp only removes one occurrence:
"hello\n\n".chomp
# => "hello\n"
"test!!!".chomp("!!")
# => "test!"
Practical Example: Processing File Lines
When reading lines from a file, chomp is essential to remove the trailing newline:
File.readlines("data.txt").each do |line|
cleaned = line.chomp
puts cleaned.upcase
end
Comparison with Strip
While chomp only removes trailing record separators, strip removes both leading and trailing whitespace:
" hello \n".chomp
# => " hello "
" hello \n".strip
# => "hello"
"\tdata\t".chomp
# => "\tdata\t"
"\tdata\t".strip
# => "data"
Comparison with Chop
The chop method removes the last character unconditionally, while chomp only removes record separators:
"hello\n".chop
# => "hell"
"hello\n".chomp
# => "hello"
"hello!".chop
# => "hell"
"hello!".chomp("!")
# => "hello"
Common Pitfall: Mutating the Original String
Remember that chomp returns a new string and does not modify the original. Use chomp! if you need in-place modification:
str = "hello\n"
str.chomp
puts str.inspect # => "hello\n"
str.chomp!
puts str.inspect # => "hello"