hal*_*dan 32
用途slice!:
s = "Hello"
s.slice!(0) #=> "ello"
Run Code Online (Sandbox Code Playgroud)
尝试一下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"
Run Code Online (Sandbox Code Playgroud)
KL-*_*L-7 19
说到效率,我从来没有很好的机会玩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
Run Code Online (Sandbox Code Playgroud)
结果如下:
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)
Run Code Online (Sandbox Code Playgroud)
似乎slice是最明显的(至少对我来说)s[1..-1]或s[1..4]稍微落后的最佳选择.使用reverse和regexp的解决方案对于这种任务看起来很复杂.
小智 10
选项1:
"abcd"[1..-1]
Run Code Online (Sandbox Code Playgroud)
选项2(更具描述性):
"abcd".last(-1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24480 次 |
| 最近记录: |