How to check string contains special character in ruby

Viewed 33757

How to check whether a string contains special character in ruby. If I get regular expression also it is fine.

Please let me know

7 Answers

Why not use inverse of [:alnum:] posix.

Here [:alnum:] includes all 0-9, a-z, A-Z.

Read more here.

"Hel@lo".index( /[^[:alnum:]]/ )

This will return nil in case you do not have any special character and hence eaiest way I think.

if you looking for a particular character, you can make a range of characters that you want to include and check if what you consider to be a special character is not part of that arsenal

puts String([*"a".."z"].join).include? "a"    #true
puts String([*"a".."z"].join).include? "$"    #false

I think this is flexible because here you are not limited as to what should be excluded

puts String([*"a".."z",*0..9,' '].join).include? " "   #true
Related