Removing the last n characters of a string in Ruby
In this tutorial, we are going to learn about how to remove the last n characters of a string in Ruby.
Consider, we have the following month
string:
month = "september"
Now, we need to remove the last 3 "ber"
characters from the end of a string.
Removing last n characters
To remove the last n characters of a string, we can use the built delete_suffix!()
method in Ruby.
The delete_suffix!()
method takes the last n characters as an argument and returns the copy of a string by deleting it.
Here is an example, that removes the last 3 characters from the month
string:
month = "september"
month.delete_suffix!("ber")
puts month
Output:
"septem"
Similarly, we can also use the slice!
method in Ruby.
Example:
month = "september"
month.slice!(-3,3)
puts month
In the above code, we have passed -3, 3
as an arguments to the slice!
method. so it removes the
last 3 characters from the end of a string.
Note: In ruby, the negative index starts from the end of a string. for example -1
is the last character index.