Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
chop
ruby
communitycreator

Removing the last character of a string in Ruby

okwudili onyejiaku

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 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
Removing the last character of a string with the "chop" method in Ruby

Code explanation

In the example above:

  • We create four strings: str1, str2, str3, and str4.
  • We call the chop method 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.

RELATED TAGS

string
chop
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring