Extracting the last n characters from a ruby string
RubyStringRuby Problem Overview
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).
Ruby Solutions
Solution 1 - Ruby
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.)
Solution 2 - Ruby
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
Solution 3 - Ruby
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"
Solution 4 - Ruby
ending = string.reverse[0...n].reverse
Solution 5 - Ruby
You can use the following code:
string[string.length-n,string.length]
Solution 6 - Ruby
To get the last n characters from a string, you could do this
a[-n, n] if a is the array.
Here's and example if you would want one.
ruby-1.9.2-p180 :006 > a = "911234567890"
=> "911234567890"
ruby-1.9.2-p180 :009 > a[-5,5]
=> "67890"
ruby-1.9.2-p180 :010 > a[-7,7]
=> "4567890"
Solution 7 - Ruby
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.
Solution 8 - Ruby
Improvement on EmFi's answer.
string[/.{,#{n}}\z/m]
Solution 9 - Ruby
I just simply use this:
str.last(n)