What are chop and chop! in Ruby?

Overview

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.

Syntax

str.chop
# AND
str.chop!

Parameters

str: The string whose last character will be removed.

Return value

The value returned is a new string containing the character removed last from the original string.

Code example

In the example below, we will create some strings and call the chop and chop! methods on them.

# create some strings
str1 = "Edpresso"
str2 = "is"
str3 = "the"
str4 = "best"
# call the chop and chop! methods
str1.chop
str2.chop
str3.chop!
str4.chop!
# print original strings
puts str1
puts str2
puts str3
puts str4

Explanation

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.

Free Resources