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 string str1 = "Hi" str2 = "Welcome\r\n" str3 = "to" str4 = "Edpresso" # call the chop method a = str1.chop b = str2.chop c = str3.chop d = str4.chop.chop # print returned values puts a puts b puts c puts 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.
RELATED TAGS
CONTRIBUTOR
View all Courses