Kernel#chomp

str.chomp([separator]) -> string
Returns: String · Updated March 13, 2026 · Kernel Methods
strings parsing io

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

ParameterTypeDefaultDescription
separatorString$/ (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 copy
text = "hello world"
text.chomp
# => "hello world"

Using chomp with custom separator

# Remove trailing slashes
path = "/usr/local/bin/"
path.chomp("/")
# => "/usr/local/bin"

# Remove multiple characters
data = "record1|record2|"
data.chomp("|")
# => "record1|record2"

Using chop

text = "hello"
text.chop
# => "hell"

# chop always removes one character
text = "hello\n"
text.chop
# => "hello"

Multiple consecutive removals

text = "hello world\n\n"
text.chomp
# => "hello world\n"

# Use chomp! (mutating version) for multiple passes
text = "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 it
File.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 whitespace
text = "hello world   \n"
text.chomp
# => "hello world   "

# For all trailing whitespace, use strip:
text.strip
# => "hello world"

Building command strings

# Common pattern: build command, ensure no trailing separator
commands = ["git add .", "git commit -m 'fix'", "git push"]
command = commands.join(" && ").chomp(" && ")
# => "git add . && git commit -m 'fix' && git push"

chomp vs chop

MethodRemovesUse case
chompRecord separator (usually \n)Processing file input, user input
chopLast character unconditionallyRemoving trailing newlines regardless of OS

See Also