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).
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
Getting the last character To access the last character of a string, we need to pass the negative index -1 to the square brackets [] in Ruby. Note: Negative index gets the data from the end of a string.
To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .
In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With