Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using gsub in ruby strings correctly

Tags:

string

ruby

gsub

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.

like image 977
banditKing Avatar asked Aug 12 '13 17:08

banditKing


People also ask

How do I use GSUB in Ruby?

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.

Does GSUB use regex?

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.

What is string GSUB?

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.

What is the difference between gsub () and sub ()?

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.


2 Answers

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

channelName = rhash["Channel"].tr("':;", " ")
like image 139
sawa Avatar answered Oct 20 '22 02:10

sawa


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(/[':;]/, " ")
like image 33
Dylan Markow Avatar answered Oct 20 '22 02:10

Dylan Markow