tags:

views:

156

answers:

3

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

A: 
ending = string.reverse[0...n].reverse
Andrew Grimm
+11  A: 

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

perimosocordiae
+1... I think this way is easier to read than `string.reverse[0..n].reverse`, which gives me a second of "wait, why is he doing that?" (or would if I weren't reading it in the context of this question)
Arkaaito
Much simpler than my regex.
EmFi
Good answer, but it should be `||` instead of `or`, or put parentheses around `str[-n..-1] or str`.
Andrew Grimm
Good answer, but I don't like that ruby doesn't treat s[-inf..-1] the same as x[0..inf]
klochner
Thanks for noting the operator precedence issue, Andrew. Gets me every time.
perimosocordiae
@perimosocordiae you aren't the only one. http://stackoverflow.com/questions/372652/what-are-the-ruby-gotchas-a-newbie-should-be-warned-about
Andrew Grimm
+1  A: 

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.

EmFi