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)
精彩评论