Ruby,从字符串中删除最后 N 个字符? [英] Ruby, remove last N characters from a string?
问题描述
从字符串中删除最后 n
个字符的首选方法是什么?
What is the preferred way of removing the last n
characters from a string?
推荐答案
Ruby 2.5+
从 Ruby 2.5 开始,您可以使用 delete_suffix
或 delete_suffix!
以快速且可读的方式实现这一点.
Ruby 2.5+
As of Ruby 2.5 you can use delete_suffix
or delete_suffix!
to achieve this in a fast and readable manner.
有关方法的文档在这里.
如果你知道后缀是什么,这是惯用的(我认为,比这里的其他答案更具可读性):
If you know what the suffix is, this is idiomatic (and I'd argue, even more readable than other answers here):
'abc123'.delete_suffix('123') # => "abc"
'abc123'.delete_suffix!('123') # => "abc"
它甚至比最佳答案快得多(使用 bang 方法几乎 40%).以下是相同基准测试的结果:
It's even significantly faster (almost 40% with the bang method) than the top answer. Here's the result of the same benchmark:
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)
我希望这很有用 - 请注意,该方法目前不接受正则表达式,因此如果您不知道后缀,则暂时不可行.但是,由于接受的答案(更新:撰写本文时)规定相同,我认为这可能对某些人有用.
I hope this is useful - note the method doesn't currently accept a regex so if you don't know the suffix it's not viable for the time being. However, as the accepted answer (update: at the time of writing) dictates the same, I thought this might be useful to some people.
这篇关于Ruby,从字符串中删除最后 N 个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!