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


当前回答

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

其他回答

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

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

查看slice()方法:

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

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

使用正则表达式:

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"