What is the chomp method in Ruby?

In Ruby, the chomp method removes the record separatora character that indicates the end of one record and beginning of the next record from the end of the string and returns the string.

A record in the computer is a collection of data items arranged for processing.

This is shown in the illustration below:

Syntax

The chomp method is declared as follows:

str.chomp

OR

str.chomp(substring)

Parameters

The chomp method either takes no arguments or just one argument. In the case of an argument, a substring is specified to be removed from the string.

Return value

The chomp method returns the string with no record separator at the end of the string.

  • If $/pre-defined variable used as the input record separator and has a default value of ā€œ\nā€ has not been changed, the chomp method will remove the carriage return characters from the string. These include \n, \r and \r\n.

  • The chomp method removes trailing newlines (\n) from a given string if $/ is empty.

Examples

The examples below show the use of the chomp method in Ruby:

#Example 1
puts "bye\n".chomp
#Example 2
puts "bye\r\n".chomp
#Example 3
puts "bye".chomp('e')
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
šŸ† Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved