从字符串中删除最后n个字符的首选方法是什么?


当前回答

你可以用

 "string".sub!(/.{X}$/,'')

其中X是要删除的字符数。

或者赋值/使用结果:

myvar = "string"[0..-X]

其中X是要删除的字符数加1。

其他回答

如果你可以创建类方法,想要删除字符,试试这个:

class String
  def chop_multiple(amount)
    amount.times.inject([self, '']){ |(s, r)| [s.chop, r.prepend(s[-1])] }
  end
end

hello, world = "hello world".chop_multiple 5
hello #=> 'hello '
world #=> 'world'
irb> 'now is the time'[0...-4]
=> "now is the "

查看slice()方法:

http://ruby-doc.org/core-2.5.0/String.html#method-i-slice

x = "my_test"
last_char = x.split('').last
str = str[0..-1-n]

不像[0…-n],它处理n=0的情况。