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
.
str.chomp(separator)
str
: The string that we want to execute.
separator
: The separator or string to remove from str
.
The chomp
method returns a new string after removing any carriage return characters.
In the example below, we will look at how to use the chomp()
method.
# create some stringsstr1 = "Meta"str2 = "Google\n"str3 = "Amazon\r\n"str4 = "Netflix\r"str5 = "Apple"# chomp the stringsa = str1.chompb = str2.chompc = str3.chompd = str4.chompe = str5.chomp("le")# print returned valuesputs aputs bputs cputs dputs e
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
.