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


当前回答

如果你想要删除的字符总是相同的字符,那么考虑chomp:

'abc123'.chomp('123')    # => "abc"

chomp的优点是:无需计数,代码可以更清楚地传达它正在做什么。

如果没有参数,chomp将删除DOS或Unix行结束符,如果它们都存在:

"abc\n".chomp      # => "abc"
"abc\r\n".chomp    # => "abc"

从评论中可以看出,使用#chomp和使用range的速度有什么不同。以下是两者的比较基准:

require 'benchmark'

S = 'asdfghjkl'
SL = S.length
T = 10_000
A = 1_000.times.map { |n| "#{n}#{S}" }

GC.disable

Benchmark.bmbm do |x|
  x.report('chomp') { T.times { A.each { |s| s.chomp(S) } } }
  x.report('range') { T.times { A.each { |s| s[0...-SL] } } }
end

基准测试结果(使用CRuby 2.13p242):

Rehearsal -----------------------------------------
chomp   1.540000   0.040000   1.580000 (  1.587908)
range   1.810000   0.200000   2.010000 (  2.011846)
-------------------------------- total: 3.590000sec

            user     system      total        real
chomp   1.550000   0.070000   1.620000 (  1.610362)
range   1.970000   0.170000   2.140000 (  2.146682)

因此,chomp比使用range快22%。

其他回答

x = "my_test"
last_char = x.split('').last
name = "my text"
x.times do name.chop! end

在控制台:

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

使用正则表达式:

str = 'string'
n = 2  #to remove last n characters

str[/\A.{#{str.size-n}}/] #=> "stri"

删除最后n个字符与保留第一个长度- n个字符相同。

主动支持包括String#first和String#last方法,它们提供了一种方便的方法来保留或删除第一个/最后一个n个字符:

require 'active_support/core_ext/string/access'

"foobarbaz".first(3)  # => "foo"
"foobarbaz".first(-3) # => "foobar"
"foobarbaz".last(3)   # => "baz"
"foobarbaz".last(-3)  # => "barbaz"

Ruby是2。5 +。

从Ruby 2.5开始,您可以使用delete_suffix或delete_suffix!以快速和可读的方式实现这一点。

关于方法的文档在这里。

如果你知道后缀是什么,这是惯用的(我认为,甚至比这里的其他答案更具可读性):

'abc123'.delete_suffix('123')     # => "abc"
'abc123'.delete_suffix!('123')    # => "abc"

它甚至比最上面的答案快得多(爆炸法几乎快了40%)。下面是相同基准测试的结果:

                     user     system      total        real
chomp            0.949823   0.001025   0.950848 (  0.951941)
range            1.874237   0.001472   1.875709 (  1.876820)
delete_suffix    0.721699   0.000945   0.722644 (  0.723410)
delete_suffix!   0.650042   0.000714   0.650756 (  0.651332)

我希望这是有用的-注意,该方法目前不接受正则表达式,所以如果你不知道后缀,它是不可行的。然而,正如公认的答案(更新:在撰写本文时)所述,我认为这可能对一些人有用。