Search code examples
rubystringapostrophe

How do you delete one apostrophe where it is duplicated in a string?


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.


Solution

  • 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("'")
    #=> " ' "