Returns String·Updated May 16, 2026·Kernel Methods
stringsparsingio
chomp and chop are String methods that remove trailing characters. The key difference: chomp removes the record separator (typically newline), while chop unconditionally removes the last character.
Syntax
string.chomp(separator=$/)string.chop
Parameters
Parameter
Type
Default
Description
separator
String
$/ (input record separator)
The string to remove from the end. Typically \n for newlines.
Examples
Basic usage with chomp
text = "hello world\n"text.chomp# => "hello world"# Without newline, chomp returns a copytext = "hello world"text.chomp# => "hello world"
text = "hello"text.chop# => "hell"# chop always removes one charactertext = "hello\n"text.chop# => "hello"
Multiple consecutive removals
text = "hello world\n\n"text.chomp# => "hello world\n"# Use chomp! (mutating version) for multiple passestext = "hello world\n\n"text.chomp!text.chomp!# => "hello world"
Common Patterns
Reading lines from a file
# Each line read by gets includes newline; chomp removes itFile.readlines("file.txt").each do |line| process(line.chomp)end# Or more concisely with chomp:File.each_line("file.txt") { |line| process(line.chomp) }
Removing trailing whitespace
# chomp only removes the separator, not all whitespacetext = "hello world \n"text.chomp# => "hello world "# For all trailing whitespace, use strip:text.strip# => "hello world"