Extracting the last n characters from a ruby string

前端 未结 8 1162
深忆病人
深忆病人 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: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.

提交回复
热议问题