I was trying to use gsub
to remove non word characters in a string in a rails app. I used the following code:
somestring.gsub(/[\W]/i, '') #=> ""
but it is actually incorrect, it will remove letter k
as well. The correct one should be:
somestring.gsub(/\W/i, '') #=> "kkk"
But my problem is that the unit test of a rails controller which contains the above code using rspec does not work, the unit test actually passes. So I created a pretty extreme test case in rspec
it "test this gsub" do
'kkk'.gsub(/[\W]/i, '').should == 'kkk'
end
the above test case should fail, but it actually passes. What is the problem here? Why would the test pass?
/[\W]/i
is a completely valid regexp for that task as far as I can see. Brackets are unnecessary in that case, but it doesn't hurt anything. – KL-7 Apr 27 '12 at 15:19irb
?"kkk".gsub(..)
it works like it should, and the result is "kkk", so the test passes. What is the result you are expecting? – Casper Apr 27 '12 at 15:20'kkk'.gsub(/[\W]/i, '')
I get""
. In comparison, running'kkk'.gsub(/\W/i, '')
returns"kkk"
. – Andrew Marshall Apr 27 '12 at 15:21k
is a "word" character. And\W
matches non-word characters. On my Ruby installation I get"kkk"
when running inirb
. – Casper Apr 27 '12 at 15:24/i
flag. Do you really need ignore-case flag for non-word characters? – KL-7 Apr 27 '12 at 15:36