I want ‘This Is A 101 Test’ to be ‘This Is A Test’, but I can’t get the syntax right.
src = 'This Is A 101 Test'
puts "A) " + src # base => "This Is A 101 Test"
puts "B) " + src[/([a-z]+)/] # only does first word => "his"
puts "C) " + src.gsub!(/\D/, "") # Does digits, I want alphabetic => "101"
puts "D) " + src.gsub!(/\W///g) # Nothing. => ""
puts "E) " + src.gsub(/(\W|\d)/, "") # Nothing. => ""
First off, you need to be careful with
gsubandgsub!. The latter is “dangerous!” and will modify the value ofsrc. If you’re executing these statements in order, be aware thata.gsub!(/a/, "b")anda = a.gsub(/a/, "b")will both do the same thing toa. Part of the issue with your code is thatsrcis being modified.The B method returns
"his"but makes no changes tosourceThe C method removes all characters that aren’t numbers:
The D method doesn’t work because the syntax is wrong. The
gsubmethod accepts a regular expression/string to search and then a string to use for replacement. If you try it in IRB it will act as though you need another/somewhere.The E method replaces all non-word characters and all numbers:
You point out that it’s returning
"". Well, what’s actually happening is that C and D as listed (with syntax issues fixed) are destructive changes. (Also, if run on"101", D will actually returnnilas no substitutions were performed.) So E is just being run on"101", and since you’re replacing all non-words and all numbers with"", it becomes"101".The answer you’re looking for would be something like:
And my favorite for dealing with all scenarios of double spaces (because
squeezeis quite efficient at combining like characters,stripis quite efficient at stripping trailing whitespace, and those!returnnilif they make no replacements):