Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do a case-insensitive `gsub`?

Tags:

I am doing a gsub to swap "bad" for "good". Is there a way to use capitalize so it will swap both lower and upper case? Or will I have to write the def twice?

def add_more_ruby(string)   string.gsub('bad','good').capitalize end 
like image 878
Stacca Avatar asked Mar 12 '15 11:03

Stacca


People also ask

What does GSUB return?

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.


1 Answers

You can pass Regexp instead of String, with i option that indicates that this regexp is case insensitive:

def add_more_ruby(string)   string.gsub(/bad/i, 'good') end 

note that it will substitute not only 'bad' and 'BAD', but also, for example, 'bAd'. If you want to substitute only all-uppercase or all-lowercase, you can do:

string.gsub(/bad|BAD/, 'good') 
like image 141
Marek Lipka Avatar answered Nov 12 '22 06:11

Marek Lipka