我有一个字符串c1234
- 删除字符串第一个字母的最有效,最快捷的方法是什么?
答案 0 :(得分:32)
使用slice!
:
s = "Hello"
s.slice!(0) #=> "ello"
在irb
:
ruby-1.9.3-p0 :001 > s = "Hello"
=> "Hello"
ruby-1.9.3-p0 :002 > s.slice!(0) #=> "ello"
=> "H"
ruby-1.9.3-p0 :003 > s
=> "ello"
答案 1 :(得分:17)
最佳解决方案将是"foobar"[1..-1]
。不需要正则表达式。
答案 2 :(得分:17)
说到效率,我从来没有很好的机会与ruby的Benchmark
模块一起玩,所以决定立即出于好奇心。这是基准:
require 'benchmark'
n = 10_000_000
s = 'c1234'
Benchmark.bm(8) do |x|
x.report('slice!') { n.times { s.dup.slice!(0) } }
x.report('slice') { n.times { s.dup.slice(1, 4) } }
x.report('[1..-1]') { n.times { s.dup[1..-1] } }
x.report('[1..4]') { n.times { s.dup[1..4] } }
x.report('reverse') { n.times { s.dup.reverse.chop.reverse } }
x.report('gsub') { n.times { s.dup.gsub(/^./, "") } }
x.report('sub') { n.times { s.dup.sub(/^./, "") } }
end
结果如下:
user system total real
slice! 7.460000 0.000000 7.460000 (7.493322)
slice 6.880000 0.000000 6.880000 (6.902811)
[1..-1] 7.710000 0.000000 7.710000 (7.728741)
[1..4] 7.700000 0.000000 7.700000 (7.717171)
reverse 10.130000 0.000000 10.130000 (10.151716)
gsub 11.030000 0.000000 11.030000 (11.051068)
sub 9.860000 0.000000 9.860000 (9.880881)
似乎slice
是最明显的选择(至少对我而言)s[1..-1]
或s[1..4]
稍微落后。使用reverse
和regexp的解决方案看起来很复杂。
答案 3 :(得分:9)
选项1:
"abcd"[1..-1]
选项2(更具描述性):
"abcd".last(-1)
答案 4 :(得分:5)
有多种方法可以做到这一点:)
"foobar".gsub(/^./, "") # => "oobar"
答案 5 :(得分:2)
到目前为止我已经采用了解决方案并创建了一个基准:
require 'benchmark'
#~ TEST_LOOPS = 10_000_000
TEST_LOOPS = 10_000
TESTSTRING = 'Hello'
Benchmark.bmbm(10) {|b|
b.report('slice!') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s.slice!(0)
} #Testloops
} #b.report
b.report('gsub^') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s.gsub(/^./, "")
} #Testloops
} #b.report
b.report('gsub\A') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s.gsub(/\A./, "")
} #Testloops
} #b.report
b.report('[1..-1]') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s = s[1..-1]
} #Testloops
} #b.report
b.report('s[0] = ""') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s[0] = ''
} #Testloops
} #b.report
b.report('reverse.chop') {
TEST_LOOPS.times {
s = TESTSTRING.dup
s = s.reverse.chop.reverse
} #Testloops
} #b.report
} #Benchmark
结果:
Rehearsal ------------------------------------------------
slice! 0.000000 0.000000 0.000000 ( 0.000000)
gsub^ 0.063000 0.000000 0.063000 ( 0.062500)
gsub\A 0.031000 0.000000 0.031000 ( 0.031250)
[1..-1] 0.000000 0.000000 0.000000 ( 0.000000)
s[0] = "" 0.015000 0.000000 0.015000 ( 0.015625)
reverse.chop 0.016000 0.000000 0.016000 ( 0.015625)
--------------------------------------- total: 0.125000sec
user system total real
slice! 0.016000 0.000000 0.016000 ( 0.015625)
gsub^ 0.046000 0.000000 0.046000 ( 0.046875)
gsub\A 0.032000 0.000000 0.032000 ( 0.031250)
[1..-1] 0.015000 0.000000 0.015000 ( 0.015625)
s[0] = "" 0.016000 0.000000 0.016000 ( 0.015625)
reverse.chop 0.016000 0.000000 0.016000 ( 0.015625)
至少不应使用正则表达式。
答案 6 :(得分:1)
如果你正在使用ruby 1.9:
s = "foobar"
s[0] = ''