String#chop!

str.chop! -> str or nil
Returns: String or nil · Updated March 13, 2026 · String Methods
strings mutation parsing

The chop! method removes the last character from a string, modifying it in place. This destructive operation is useful when you need to clean up trailing characters from user input, file content, or any string data that might have unwanted terminators.

How It Works

When you call chop! on a string, it removes the final character and returns the modified string. If the string is empty, chop! returns nil instead of an empty string. Unlike chomp! which removes record separators (typically newlines), chop! removes absolutely any last character regardless of what it is.

This method is particularly useful in scenarios where you’re processing input that might have inconsistent trailing characters, or when you need to strip exactly one character from the end of a string without caring what that character is.

Practical Examples

Basic Usage

# Remove the last character from a string
text = "hello"
text.chop!  # => "hell"
puts text   # => "hell" (modified in place)

# Works with any characters
"ruby!".chop!   # => "ruby"
"12345".chop!   # => "1234"
"a\nb".chop!    # => "a\n" (removes 'b', not the newline)

Handling Empty Strings

# Empty strings return nil
"".chop!        # => nil
"a".chop!       # => "" (not nil, because it has one char)

Processing File Lines

# When reading lines, each line typically ends with a newline
lines = ["first line\n", "second line\n", "third line\n"]
lines.each { |line| line.chop! }
# => ["first line", "second line", "third line"]

# This is useful for cleaning up CSV data
csv_row = "John,Doe,30\n"
csv_row.chop!
puts csv_row.split(",")  # => ["John", "Doe", "30"]

User Input Processing

# Clean up user input that might have unexpected characters
def normalize_input(input)
  input.chop! while input.end_with?(" ", "\t", "\n")
  input
end

normalize_input("username   ")  # => "username"
normalize_input("email\t\n")    # => "email"

Important Notes

The chop! method modifies the original string. If you need a non-destructive version that returns a new string, use chop (without the bang). Also be aware that chop treats the string as a sequence of characters and removes exactly one character from the end, unlike chomp which removes record separators.

# Non-destructive alternative
original = "hello"
modified = original.chop
puts original  # => "hello" (unchanged)
puts modified  # => "hell"

This method has been part of Ruby’s String class since early versions and remains a fundamental tool for string manipulation tasks.

See Also