Get the last n characters of a string in Ruby
In this tutorial, we are going to learn about how to get the last n characters of a given string in Ruby.
Consider, we have the following string:
name = "alisha"
Now, we need to get the last 3 characters sha
from the above string.
In Ruby, strings are a sequence of characters, where the first character index is [0]
, the second character index [1]
, etc and negative indexes are used to access the characters from the end of a string.
Getting the last n characters
To access the first n characters of a string in ruby, we can use the square brackets syntax []
by passing the start index and length.
Note: Negative index gets the data from the end of a string.
Here is an example, that gets the last 3 characters sha
from the following string:
name = "alisha"
lastThreeChars = name[-3 ,3]
puts lastThreeChars
Output:
"sha"
In the example above, we have passed the name[-3, 3] to the square brackets syntax.Where ‘-3’ is start index, so, it begins the character extraction from the end of a string and extracts upto 3 characters from the start index.