[SOLVED] Extracting the last n characters from a ruby string


To get the last n characters from a string, I assumed you could use

ending = string[-n..-1]

but if the string is less than n letters long, you get nil.

What workarounds are available?

Background: The strings are plain ASCII, and I have access to ruby 1.9.1, and I’m using Plain Old Ruby Objects (no web frameworks).


Here you have a one liner, you can put a number greater than the size of the string:


For ruby 1.9+


For ruby 2.0+, join returns a string


Answered By – Gareve

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *