Ruby: backslash all non-alphanumeric characters in a string

Posted by HBlend on Stack Overflow See other posts from Stack Overflow or by HBlend
Published on 2011-02-10T07:37:21Z Indexed on 2011/02/10 15:25 UTC
Read the original article Hit count: 264

Filed under:
|

I have a script where I need to take a user's password and then run a command line using it. I need to backslash all (could be more then one) non-alphanumeric characters in the password. I have tried several things at this point including the below but getting no where. This has to be easy, just missing it.

Tried these and several others:

password = password.gsub(/(\W)/, '\\1')

password = password.gsub(/(\W)/, '\\\1')

password = password.gsub(/(\W)/, '\\\\1')

© Stack Overflow or respective owner

Related posts about ruby

Related posts about regex