Stripping non alphanumeric characters

I know this is a noob question. What would be the best / most efficient
way to replace all non alphanumeric characters in a string?

Thanks for your help.

Ben J. wrote:

I know this is a noob question. What would be the best / most efficient
way to replace all non alphanumeric characters in a string?

Thanks for your help.

you didn’t say what you want to replace them with. Here I assumed you
want to remove them. But you could use anything instead of just ‘’ in
the 2nd argument to gsub.

ruby$ irb
irb(main):001:0> x = “ab*&12%^cd”
=> “ab*&12%^cd”
irb(main):002:0> x.gsub(/[^[:alnum:]]/, ‘’)
=> “ab12cd”

You’re the man, thanks.