The chop
and chop!
methods in Ruby are both used to remove the last character of a string. If the string ends with \r\n
, both characters will be removed. Both methods return an empty string if they are called on an empty string.
The difference between the two is that while chop!
will permanently modify the string on which it is called, chop
won’t.
str.chop
# AND
str.chop!
str
: The string whose last character will be removed.
The value returned is a new string containing the character removed last from the original string.
In the example below, we will create some strings and call the chop
and chop!
methods on them.
# create some stringsstr1 = "Edpresso"str2 = "is"str3 = "the"str4 = "best"# call the chop and chop! methodsstr1.chopstr2.chopstr3.chop!str4.chop!# print original stringsputs str1puts str2puts str3puts str4
In the code above, we can see that chop!
actually modified the strings str3
and str4
. But chop
did not modify the original strings str1
and str2
.