using gsub in ruby strings correctly

banditKing picture banditKing · Aug 12, 2013 · Viewed 34k times · Source

I have this expression:

channelName = rhash["Channel"].gsub("'", " ")

it works fine. However, I can only substitute 1 character with it. I want to add a few more characters to substitue. So I tried the following:

channelName = rhash["Channel"].gsub(/[':;] /, " ")

This did not work, that is there was no substitution done on strings and no error message. I also tried this:

channelName = rhash["Channel"].gsub!("'", " ")

This lead to a string that was blank. So absolutely not what I desired.

I would like to have a gsub method to substitute the following characters with a space in my string:

 ' ; :

My questions:

  1. How can I structure my gsub method so that all instances of the above characters are replaced with a space?

  2. What is happening with gsub! above as its returning a blank.

Answer

Dylan Markow picture Dylan Markow · Aug 12, 2013

Your second attempt was very close. The problem is that you left a space after the closing bracket, meaning it was only looking for one of those symbols followed by a space.

Try this:

channelName = rhash["Channel"].gsub(/[':;]/, " ")