Removing the last character of a string in Ruby
Overview
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.
Syntax
str.chop
Parameters
This method does not take any parameters. It is invoked by the string object.
Return value
The value returned is the same string, but with its last character removed.
Example
# 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
Code explanation
In the example above:
- We create four strings:
str1,str2,str3, andstr4. - We call the
chopmethod on them in lines 8–11. - We print the returned values in lines 14–17 and discover that their last characters were removed.
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.