Step 1: Bookmark this . Whenever I need to search for regular expressions, this is my first stop
Step 2: Skip through your code
text.gsub(/\s/, "-")
You call the gsub function and provide it with 2 parameters.
The first parameter is /\s/ , which is ruby โโfor "create new regexp containing \s (// as special" "for regular expressions).
The second parameter is the string "-" .
This will replace all whitespace with hyphens. So far so good.
.gsub([^\W-], '').downcase
Then you call gsub again, passing 2 parameters to it. The first parameter is [^\W-] . Since we did not quote it in distortions, the ruby โโwill literally try to run this code. [] creates an array, and then tries to put ^\W- into the array, which is invalid code, so it breaks.
Changing it to /[^\W-]/ gives the correct regular expression.
Looking at the regular expression, [] says that it matches any character in this group. The group contains \W (which means a non-word character) and - , so the regular expression must match any character other than a word, or any hyphen.
As the second thing you pass to gsub is an empty string, it should eventually replace all characters and hyphens without words with an empty string (thereby deleting them)
.downcase
Which only converts the string to lowercase.
Hope this helps :-)
Orion edwards
source share