Deleting all special characters from a string - ruby

kwoskowicz picture kwoskowicz · Jan 30, 2014 · Viewed 65.3k times · Source

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

Answer

Alok Anand picture Alok Anand · Jan 30, 2014

You can do this

a.gsub!(/[^0-9A-Za-z]/, '')