Extracting the last n characters from a ruby string

前端 未结 8 1153
深忆病人
深忆病人 2020-12-13 11:58

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

相关标签:
8条回答
  • 2020-12-13 12:04

    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"
    
    0 讨论(0)
  • 2020-12-13 12:05

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

    0 讨论(0)
  • 2020-12-13 12:09

    You can use the following code:

    string[string.length-n,string.length]
    
    0 讨论(0)
  • 2020-12-13 12:10

    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.

    0 讨论(0)
  • 2020-12-13 12:15

    Improvement on EmFi's answer.

    string[/.{,#{n}}\z/m]
    
    0 讨论(0)
  • 2020-12-13 12:25
    ending = string.reverse[0...n].reverse
    
    0 讨论(0)
提交回复
热议问题