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


当前回答

name = "my text"
x.times do name.chop! end

在控制台:

>name = "Nabucodonosor"
 => "Nabucodonosor" 
> 7.times do name.chop! end
 => 7 
> name
 => "Nabuco" 

其他回答

str = str[0..-1-n]

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

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

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'
name = "my text"
x.times do name.chop! end

在控制台:

>name = "Nabucodonosor"
 => "Nabucodonosor" 
> 7.times do name.chop! end
 => 7 
> name
 => "Nabuco" 

查看slice()方法:

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

irb> 'now is the time'[0...-4]
=> "now is the "