Delete individual parts of a string in Ruby

I have a String str = "abcdefghij"and I want to set str2to str minus the 4-6th character (assuming an index based on 0).

Is it possible to do this at a time? slice!seems to do this, but it requires at least 3 operators (duplication, slicing, and then using a string).

+3
source share
3 answers

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)
+1
source

The usual way is as follows:

str = "abcdefghij"
str2 = str.dup
str2[4..6] = ''
# => "abcdhij"

but it still requires two steps.

If the range you want is continuous, you can do it in one step

str2 = str[2..5]
# => "cdef"
+2

, , http://ruby-doc.org/core/classes/String.html#M001201 .

, :

"abcdefghij".sub(/(.{4}).{2}/) { $1 }

.

+1

All Articles