Extracting the last n characters from a ruby string

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

    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
    

提交回复
热议问题