-2

In ruby, say I have this string: "abc''xyz''"

(those are 2 single quotes after abc and xyz)

Now, I am trying to find a way to make it into this string: "abc'xyz'"

I want to delete only one apostrophe from this string in locations where there are two apostrophes back to back. Thanks in advance.

Stefan
  • 96,300
  • 10
  • 122
  • 186
athill16
  • 33
  • 6

2 Answers2

4

You can use String#squeeze:

"abc''xyz''".squeeze("'")
#=> "abc'xyz'"

This method removes duplicates of a certain character if they are immediately after each other. It will reduce n characters in a row to just one.

For example, if you had the string " '''''' ", squeezing it would return the following:

" '''''' ".squeeze("'")
#=> " ' "
Piccolo
  • 1,473
  • 2
  • 21
  • 35
  • That's very handy. – Sebastian Palma Jun 12 '17 at 19:34
  • Hi @athill16 if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Piccolo Jun 12 '17 at 19:57
-1

String#squeeze is what you need and gsub is really a bad idea.

Benchmark.bm do |bm|

  bm.report("squeeze") do
    iterations.times do
      "e''eee''e'e''''e".squeeze("'")
    end
  end

  bm.report("gsub") do
    iterations.times do
      "e''eee''e'e''''e".gsub(/\'+/, "'")
    end
  end
end

And results:

        user       system     total     real
squeeze 6.109000   0.000000   6.109000  (  6.110040)
gsub    22.454000  0.000000   22.454000 ( 22.469204)
Sisyphe
  • 116
  • 1
  • 12