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 = "september"
Now, we need to remove the last 3
"ber" characters from the end of a string.
To remove the last n characters of a string, we can use the built
delete_suffix!() method in Ruby.
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 = "september" month.delete_suffix!("ber") puts month
Similarly, we can also use the
slice! method in Ruby.
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.