Extracting the last n characters from a ruby string

Viewed 95905

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

9 Answers

Well, the easiest workaround I can think of is:

ending = str[-n..-1] || str

(EDIT: The or operator has lower precedence than assignment, so be sure to use || instead.)

ending = string.reverse[0...n].reverse

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.

I just simply use this:

str.last(n)
Related