Get last character in string

UPDATE:
I keep getting constant up votes on this, hence the edit. Using [-1, 1] is correct, however a better looking solution would be using just [-1]. Check Oleg Pischicov’s answer.

line[-1]
# => "c"

Original Answer

In ruby you can use [-1, 1] to get last char of a string. Here:

line = "abc;"
# => "abc;"
line[-1, 1]
# => ";"

teststr = "some text"
# => "some text"
teststr[-1, 1]
# => "t"

Explanation:
Strings can take a negative index, which count backwards from the end
of the String, and an length of how many characters you want (one in
this example).

Using String#slice as in OP’s example: (will work only on ruby 1.9 onwards as explained in Yu Hau’s answer)

line.slice(line.length - 1)
# => ";"
teststr.slice(teststr.length - 1)
# => "t"

Let’s go nuts!!!

teststr.split('').last
# => "t"
teststr.split(//)[-1]
# => "t"
teststr.chars.last
# => "t"
teststr.scan(/.$/)[0]
# => "t"
teststr[/.$/]
# => "t"
teststr[teststr.length-1]
# => "t"

Leave a Comment