Extracting the last n characters from a ruby string

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

    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"

提交回复
热议问题