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


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


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

In straight Ruby (without Rails), you can do

string.chars.last(n).join

For example:

2.4.1 :009 > a = 'abcdefghij'
 => "abcdefghij"
2.4.1 :010 > a.chars.last(5).join
 => "fghij"
2.4.1 :011 > a.chars.last(100).join
 => "abcdefghij"

If you're using Ruby on Rails, you can call methods first and last on a string object. These methods are preferred as they're succinct and intuitive.

For example:

[1] pry(main)> a = 'abcdefg'                                                                                                                
 => "abcdefg"
[2] pry(main)> a.first(3)                                                                                                                   
 => "abc"
[3] pry(main)> a.last(4)                                                                                                                    
 => "defg"