Deleting all special characters from a string - ruby
I was doing the challenges from pythonchallenge writing code in ruby, specifically this one. It contains a really long string in page source with special characters. I was trying to find a way to delete them/check for the alphabetical chars.
I tried using scan method, but I think I might not use it properly. I also tried delete!
like that:
a = "PAGE SOURCE CODE PASTED HERE"
a.delete! "!", "@" #and so on with special chars, does not work(?)
a
How can I do that?
Thanks
You can do this
a.gsub!(/[^0-9A-Za-z]/, '')
try with gsub
a.gsub!(/[!@%&"]/,'')
try the regexp on rubular.com
if you want something more general you can have a string with valid chars and remove what's not in there:
a.gsub!(/[^abcdefghijklmnopqrstuvwxyz ]/,'')
When you give multiple arguments to string#delete
, it's the intersection of those arguments that is deleted. a.delete! "!", "@"
deletes the intersections of the sets !
and @
which means that nothing will be deleted and the method returns nil
.
What you wanted to do is a.delete! "!@"
with the characters to delete passed as a single string.
Since the challenge is asking to clean up the mess and find a message in it, I would go with a whitelist instead of deleting special characters. The delete method accepts ranges with -
and negations with ^
(similar to a regex) so you can do something like this: a.delete! "^A-Za-z "
.
You could also use regular expressions as shown by @arieljuod.
gsub
is one of the most used Ruby methods in the wild.
specialname="Hello!#$@"
cleanedname = specialname.gsub(/[^a-zA-Z0-9\-]/,"")