In Ruby, you can use indexing with the length of the string minus one to get the last character.
If given string is in x
and we would like to access the last character in the string, then the expression x[x.length - 1]
returns the last character.
In this example,
str
with a value of "Hello World"
.str
and str.length - 1
to get the last character.str = "Hello World"
last_char = str[str.length - 1]
puts "Last character of the string is: #{last_char}"
Last character of the string is: d
In this example,
str
with a value of "apple"
.str
and str.length - 1
to get the last character.str = "apple"
last_char = str[str.length - 1]
puts "Last character of the string is: #{last_char}"
Last character of the string is: e
In this tutorial, we learned How to get Last Character in String in Ruby language using array-like indexing, and index = length of string minus 1, with well detailed examples.