0

I have a dynamically generated string which can have any number of ":" in-between them example.

example1: "test string:: this is test string"
example2: "test string:::: this is test string"

I want to convert such string into following

result string1: "test string: this is test string"
result string2: "test string: this is test string"

Please help

2
  • 1
    You should remove the Rails tags as this is a pure-Ruby question. Readers filter questions by their tags. The Rails tags might attract readers who are only interested in Rails questions, wasting their time. It might also cause the question to not be seen by readers who are only interested in pure-Ruby questions, because they have filtered out Rails questions. (I see you removed the Rails tags, but I'll leave this comment up because tags are misused a lot.) Commented Feb 19, 2017 at 6:44
  • 2
    I see you just accepted my answer. I'm afraid I have another complaint! :-) I often rail at askers when they quickly award the checkmark, often when only one answer has been posted. I can't very well say that's OK this time, just because it was my answer that was chosen. Rapido selections can discourage other answers, are, imo, discourteous to those still preparing answers and might result in incorrect answers left unchallenged. There's no rush, so please consider waiting at least a couple of hours in future (and/or remove the present checkmark for the time being). Up to you, of course. Commented Feb 19, 2017 at 6:56

1 Answer 1

5

Use String#squeeze.

"test string:::: this is test string".squeeze(':')
  #=> "test string: this is test string"

"test string:::: this is:: test string".squeeze(':')
  #=> "test string: this is: test string"

Another way is to use String#gsub (or String#sub if there is at most one run of colons in the string).

"test string:::: this is:: test string".gsub(/:+/, ':')
  #=> "test string: this is: test string"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.