10
votes

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.

2
Whitespace matters a lot in a regular expression... - meagar
@meagar Unless you use the x option correct? ruby-doc.org/core-2.0/Regexp.html#label-Options - squiguy
Why not use String#tr for simple things like this? - mu is too short
@muistooshort awesome, thanks. Yes I didnt even look at that method. This is why I like SO, there is always a new way of solving a problem to learn about....... Thanks! I will try that. One quick question. Is the "tr" method more efficient than gsub? - banditKing
tr is probably faster than gsub but (a) regex engines can be surprisingly fast, (b) the difference is probably irrelevant for all practical purposes, and (c) you could always benchmark it and see. - mu is too short

2 Answers

18
votes

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(/[':;]/, " ")
5
votes

This does not answer your question, but is a better way to do it.

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