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
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"
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.)
You can use the following code:
string[string.length-n,string.length]
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.
Improvement on EmFi's answer.
string[/.{,#{n}}\z/m]
ending = string.reverse[0...n].reverse