可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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).
回答1:
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
回答2:
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.)
回答3:
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"
回答4:
ending = string.reverse[0...n].reverse
回答5:
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"
回答6:
You can use the following code:
string[string.length-n,string.length]
回答7:
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.
回答8:
Improvement on EmFi's answer.
string[/.{,#{n}}\z/m]