Open In App

How to Remove Last Character from String in Ruby?

Last Updated : 28 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Removing the last character from a string in Ruby is a common task in various programming scenarios. Whether you need to manipulate user input, process file paths, or clean up data, there are several approaches to achieve this. This article focuses on discussing how to remove the last character from a string in Ruby.

Using String Slicing

Below is the Ruby program to remove the last character from a string using string slicing:

Ruby
# Ruby program to remove last character 
# from string using string slicing
def remove_last_character(str)
  str[0..-2]
end

string = 'Hello World'
puts remove_last_character(string)

Output
Hello Worl

Explanation:

  1. This approach involves using string slicing to extract all characters except the last one.
  2. We specify the range 0..-2, which includes all characters from index 0 to the second-to-last character.

Using Chopping

Below is the Ruby program to remove last character from a string using chopping:

Ruby
# Ruby program to remove last character 
# from a string using chopping
def remove_last_character(str)
  str.chop
end

string = 'Hello World'
puts remove_last_character(string)

Output
Hello Worl

Explanation:

  1. The chop method removes the last character from the string and returns the modified string.
  2. It operates destructively on the original string.

Using Regular Expression

Below is the Ruby program to remove last character from a string using regular expression:

Ruby
# Ruby program to remove last character 
# from a string using regular expression
def remove_last_character(str)
  str.sub(/.$/, '')
end

string = 'Hello World'
puts remove_last_character(string)

Output
Hello Worl

Explanation:

  1. We use a regular expression /$/ to match the last character of the string.
  2. The sub method replaces the matched character with an empty string, effectively removing it.

Using Chop with Bang Method

Below is the Ruby program to remove last character from a string using chop with bang method:

Ruby
# Ruby program to remove last character 
# from a string using chop with bang method
def remove_last_character(str)
  str.chop!
end

string = 'Hello World'
puts remove_last_character(string)

Output
Hello Worl

Explanation:

  1. The chop! method removes the last character from the string in place.
  2. It modifies the original string and returns nil if no removal is made.

Conclusion

Removing the last character from a string in Ruby can be accomplished using various methods, including string slicing, chopping, regular expressions, and destructive methods.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads