To get the last n characters from a string, I assumed you could use
n
ending = string[-n..-1]
but if the string is less than
Have you tried a regex?
string.match(/(.{0,#{n}}$)/) ending=$1
The regex captures as many characters it can at the end of the string, but no more than n. And stores it in $1.