Ruby,从字符串中移除最后的N个字符?

时间:2021-05-05 17:07:23

What is the preferred way of removing the last n characters from a string?

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

12 个解决方案

#1


228  

If the characters you want to remove are always the same characters, then consider chomp:

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

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

The advantages of chomp are: no counting, and the code more clearly communicates what it is doing.

chomp的优点是:没有计算,代码更清楚地表达了它正在做什么。

With no arguments, chomp removes the DOS or Unix line ending, if either is present:

没有参数,chomp删除DOS或Unix行结束,如果有的话:

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

From the comments, there was a question of the speed of using #chomp versus using a range. Here is a benchmark comparing the two:

在评论中,有一个关于使用#chomp和使用范围的速度的问题。这里有一个比较两者的基准:

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

Benchmark Results (using CRuby 2.13p242):

基准测试结果(使用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)

So chomp is faster than using a range, by ~22%.

所以chomp的速度要快于使用范围的22%。

#2


282  

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

#3


48  

str = str[0...-n]

#4


27  

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

Here in the console:

在控制台:

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

#5


24  

I would suggest chop. I think it has been mentioned in one of the comments but without links or explanations so here's why I think it's better:

我建议。我想这是在评论中提到的但没有链接或解释,所以我认为这是更好的原因:

It simply removes the last character from a string and you don't have to specify any values for that to happen.

它简单地从字符串中删除最后一个字符,并且不需要为其指定任何值。

If you need to remove more than one character then chomp is your best bet. This is what the ruby docs have to say about chop:

如果你需要移除不止一个字符,那么chomp是你最好的选择。这就是ruby文档中关于chop的内容:

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

返回带有最后一个字符的新字符串。如果字符串以\r\n结束,两个字符都将被删除。对空字符串应用chop将返回空字符串。字符串#chomp通常是一个更安全的选择,因为它不会在记录分隔符的情况下保持字符串不变。

Although this is used mostly to remove separators such as \r\n I've used it to remove the last character from a simple string, for example the s to make the word singular.

虽然这主要用于删除分隔符,例如\r\n,但我使用它来从一个简单的字符串中删除最后一个字符,例如s使单词单数。

#6


9  

Dropping the last n characters is the same as keeping the first length - n characters.

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

Active Support includes String#first and String#last methods which provide a convenient way to keep or drop the first/last n characters:

主动支持包括字符串#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"

#7


5  

if you are using rails, try:

如果您正在使用rails,请尝试:

"my_string".last(2) # => "ng"

[EDITED]

(编辑)

To get the string WITHOUT the last 2 chars:

在没有最后两个字符的情况下得到字符串:

n = "my_string".size
"my_string"[0..n-3] # => "my_stri"

Note: the last string char is at n-1. So, to remove the last 2, we use n-3.

注意:最后一个字符串char在n-1处。因此,要移除最后的2,我们使用n-3。

#8


3  

Check out the slice() method:

检查切片()方法:

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

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

#9


2  

You can always use something like

你可以用一些类似的东西。

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

Where X is the number of characters to remove.

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

Or with assigning/using the result:

或分配/使用结果:

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

where X is the number of characters plus one to remove.

其中X是字符的数目加上一个移除。

#10


1  

If you're ok with creating class methods and want the characters you chop off, try this:

如果您可以创建类方法,并希望您的字符被删除,可以尝试以下方法:

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'

#11


0  

Using regex:

使用正则表达式:

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

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

#12


-2  

x = "my_test"
last_char = x.split('').last

#1


228  

If the characters you want to remove are always the same characters, then consider chomp:

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

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

The advantages of chomp are: no counting, and the code more clearly communicates what it is doing.

chomp的优点是:没有计算,代码更清楚地表达了它正在做什么。

With no arguments, chomp removes the DOS or Unix line ending, if either is present:

没有参数,chomp删除DOS或Unix行结束,如果有的话:

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

From the comments, there was a question of the speed of using #chomp versus using a range. Here is a benchmark comparing the two:

在评论中,有一个关于使用#chomp和使用范围的速度的问题。这里有一个比较两者的基准:

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

Benchmark Results (using CRuby 2.13p242):

基准测试结果(使用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)

So chomp is faster than using a range, by ~22%.

所以chomp的速度要快于使用范围的22%。

#2


282  

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

#3


48  

str = str[0...-n]

#4


27  

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

Here in the console:

在控制台:

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

#5


24  

I would suggest chop. I think it has been mentioned in one of the comments but without links or explanations so here's why I think it's better:

我建议。我想这是在评论中提到的但没有链接或解释,所以我认为这是更好的原因:

It simply removes the last character from a string and you don't have to specify any values for that to happen.

它简单地从字符串中删除最后一个字符,并且不需要为其指定任何值。

If you need to remove more than one character then chomp is your best bet. This is what the ruby docs have to say about chop:

如果你需要移除不止一个字符,那么chomp是你最好的选择。这就是ruby文档中关于chop的内容:

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

返回带有最后一个字符的新字符串。如果字符串以\r\n结束,两个字符都将被删除。对空字符串应用chop将返回空字符串。字符串#chomp通常是一个更安全的选择,因为它不会在记录分隔符的情况下保持字符串不变。

Although this is used mostly to remove separators such as \r\n I've used it to remove the last character from a simple string, for example the s to make the word singular.

虽然这主要用于删除分隔符,例如\r\n,但我使用它来从一个简单的字符串中删除最后一个字符,例如s使单词单数。

#6


9  

Dropping the last n characters is the same as keeping the first length - n characters.

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

Active Support includes String#first and String#last methods which provide a convenient way to keep or drop the first/last n characters:

主动支持包括字符串#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"

#7


5  

if you are using rails, try:

如果您正在使用rails,请尝试:

"my_string".last(2) # => "ng"

[EDITED]

(编辑)

To get the string WITHOUT the last 2 chars:

在没有最后两个字符的情况下得到字符串:

n = "my_string".size
"my_string"[0..n-3] # => "my_stri"

Note: the last string char is at n-1. So, to remove the last 2, we use n-3.

注意:最后一个字符串char在n-1处。因此,要移除最后的2,我们使用n-3。

#8


3  

Check out the slice() method:

检查切片()方法:

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

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

#9


2  

You can always use something like

你可以用一些类似的东西。

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

Where X is the number of characters to remove.

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

Or with assigning/using the result:

或分配/使用结果:

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

where X is the number of characters plus one to remove.

其中X是字符的数目加上一个移除。

#10


1  

If you're ok with creating class methods and want the characters you chop off, try this:

如果您可以创建类方法,并希望您的字符被删除,可以尝试以下方法:

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'

#11


0  

Using regex:

使用正则表达式:

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

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

#12


-2  

x = "my_test"
last_char = x.split('').last