How to check string contains special character in ruby

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

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

Read more here.


"foobar".include?('a')
# => true

Use str.include?.

Returns true if str contains the given string or character.

"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true

special = "?<>',?[]}{=-)(*&^%$#`~{}"
regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/

You can then use the regex to test if a string contains the special character:

if some_string =~ regex

This looks a bit complicated: what's going on in this bit

special.gsub(/./){|char| "\\#{char}"}

is to turn this

"?<>',?[]}{=-)(*&^%$#`~{}"

into this:

"\\?\\<\\>\\'\\,\\?\\[\\]\\}\\{\\=\\-\\)\\(\\*\\&\\^\\%\\$\\#\\`\\~\\{\\}"

Which is every character in special, escaped with a \ (which itself is escaped in the string, ie \\ not \). This is then used to build a regex like this:

/[<every character in special, escaped>]/