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

Issue

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).

Solution

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

"123".split(//).last(5).to_s

For ruby 1.9+

"123".split(//).last(5).join("").to_s

For ruby 2.0+, join returns a string

"123".split(//).last(5).join

Answered By – Gareve

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

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