Removing the last n characters of a string in Ruby
In this post we will give you information about Removing the last n characters of a string in Ruby. Hear we will give you detail about Removing the last n characters of a string in RubyAnd how to use it also give you demo for it if it is necessary.
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 thelast 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.
Hope this code and post will helped you for implement Removing the last n characters of a string in Ruby. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs