The chop
method is used to remove the last character of a string in Ruby. If the string ends with \r\n
, it will remove both the separators. If an empty string calls this method, then an empty string is returned.
We can call the chop
method on a string twice.
str.chop
This method does not take any parameters. It is invoked by the string object.
The value returned is the same string, but with its last character removed.
# create some stringstr1 = "Hi"str2 = "Welcome\r\n"str3 = "to"str4 = "Edpresso"# call the chop methoda = str1.chopb = str2.chopc = str3.chopd = str4.chop.chop# print returned valuesputs aputs bputs cputs d
In the example above:
str1
, str2
, str3
, and str4
.chop
method on them in lines 8–11.The chop
method removed the \r\n
from the end of str2
and the last two characters from str4
because the chop
method was called on it twice.