I continued to use the following:
str = "abcdefghij"
str2 = str[0, 4] + str[7..-1]
It turned out to be faster and cleaner than the other solutions presented. Here is a mini test.
require 'benchmark'
str = "abcdefghij"
times = 1_000_000
Benchmark.bmbm do |bm|
bm.report("1 step") do
times.times do
str2 = str[0, 4] + str[7..-1]
end
end
bm.report("3 steps") do
times.times do
str2 = str.dup
str2[4..6] = ''
str2
end
end
end
Released on Ruby 1.9.2
Rehearsal -------------------------------------------
1 step 0.950000 0.010000 0.960000 ( 0.955288)
3 steps 1.250000 0.000000 1.250000 ( 1.250415)
---------------------------------- total: 2.210000sec
user system total real
1 step 0.960000 0.000000 0.960000 ( 0.950541)
3 steps 1.250000 0.010000 1.260000 ( 1.254416)
Edit: update for <<.
Script:
require 'benchmark'
str = "abcdefghij"
times = 1_000_000
Benchmark.bmbm do |bm|
bm.report("1 step") do
times.times do
str2 = str[0, 4] + str[7..-1]
end
end
bm.report("3 steps") do
times.times do
str2 = str.dup
str2[4..6] = ''
str2
end
end
bm.report("1 step using <<") do
times.times do
str2 = str[0, 4] << str[7..-1]
end
end
end
Released on Ruby 1.9.2
Rehearsal ---------------------------------------------------
1 step 0.980000 0.010000 0.990000 ( 0.979944)
3 steps 1.270000 0.000000 1.270000 ( 1.265495)
1 step using << 0.910000 0.010000 0.920000 ( 0.909705)
------------------------------------------ total: 3.180000sec
user system total real
1 step 0.980000 0.000000 0.980000 ( 0.985154)
3 steps 1.280000 0.000000 1.280000 ( 1.281310)
1 step using << 0.930000 0.000000 0.930000 ( 0.916511)
source
share