开发者

what is the best way to remove the last n characters of a string (in Ruby)? [duplicate]

开发者 https://www.devze.com 2023-01-03 14:46 出处:网络
This question already has answers here: Ruby, remove last N characters from a string? (13 answers) Closed 5 years ago.
This question already has answers here: Ruby, remove last N characters from a string? (13 answers) Closed 5 years ago.

in Ruby, I just want to get rid of the last n characters of a string, but the following doesn't work

"string"[0,-3]

nor

"string".slice(0, -开发者_如何学Go3)

I'd like a clean method, not anything like

"string".chop.chop.chop

it may be trivial, please anyone teach me! thanks!


You can use ranges.

"string"[0..-4]


You could use a regex with gsub ...

"string".gsub( /.{3}$/, '' )


If you add an ! to slice it will destructively remove the last n characters without having to assign it to another variable:

my_string.slice!(my_string.length-3,my_string.length)

compared to:

new = my_string.slice(0..-4)
0

精彩评论

暂无评论...
验证码 换一张
取 消