How to use the chomp() method in Ruby

The chomp method in Ruby is used to return a new string from a string after it has removed any record separators (/r).

By default, if no parameter is passed, chomp will remove any carriage returns such as \n, \r, and \r\n.

Syntax

str.chomp(separator)

Parameters

  • str: The string that we want to execute.

  • separator: The separator or string to remove from str.

Return value

The chomp method returns a new string after removing any carriage return characters.

Code

In the example below, we will look at how to use the chomp() method.

# create some strings
str1 = "Meta"
str2 = "Google\n"
str3 = "Amazon\r\n"
str4 = "Netflix\r"
str5 = "Apple"
# chomp the strings
a = str1.chomp
b = str2.chomp
c = str3.chomp
d = str4.chomp
e = str5.chomp("le")
# print returned values
puts a
puts b
puts c
puts d
puts e

Explanation

  • Lines 2-6: We create several strings and initialize them with values.

  • Lines 9-12: We call the chomp method on the created strings.

  • Line 13: We pass a parameter "le" to the chomp method called by string str5.

In the code above, all carriage return characters are removed with the chomp method. We pass a default separator to remove the le in Apple.

Free Resources