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 fromstr.
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 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
Explanation
-
Lines 2-6: We create several strings and initialize them with values.
-
Lines 9-12: We call the
chompmethod on the created strings. -
Line 13: We pass a parameter
"le"to thechompmethod called by stringstr5.
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.