find the last character in a string in ruby

To find the last character in a string in ruby, you can use the String#[] method with -1 as the argument. This accesses the element at index -1, which is the last character in the string.

main.rb
string = "hello"
last_char = string[-1]
# last_char now contains the value "o"
79 chars
4 lines

You can also use the String#slice method with the same argument:

main.rb
string = "hello"
last_char = string.slice(-1)
# last_char now contains the value "o"
85 chars
4 lines

Either of these methods will give you the last character in a ruby string.

related categories

gistlibby LogSnag