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:
How can I structure my gsub method so that all instances of the above characters are replaced with a space?
What is happening with gsub! above as its returning a blank.
gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.
Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do. In Ruby, they are always contained within two forward slashes.
gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.
The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.
This does not answer your question, but is a better way to do it.
channelName = rhash["Channel"].tr("':;", " ")
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(/[':;]/, " ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With