You don't need to escape any of the characters in your character class:
special = "[;\`'<>-]"
regex = /#{special}/
p regex
#pi = ARGV[0] #takes in console argument to test
pi = 'hello;world'
if pi == '3.1415926535897932385'
puts "got it"
end
if pi =~ regex
puts "stop word"
else
puts "incorrect"
end
--output:--
/[;`'<>-]/
stop word
And ARGV[0]
is a string already. But, a shell/console also recognizes special characters when you enter them on the command line:
special = "[;\`'<>-]"
#regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/
regex = /#{special}/
p regex
pi = ARGV[0] #takes in console argument to test
if pi == '3.1415926535897932385'
puts "got it"
end
if pi =~ regex
puts "stop word"
else
puts "incorrect"
end
--output:--
~/ruby_programs$ ruby 1.rb ;
/[;`'<>-]/
incorrect
~/ruby_programs$ ruby 1.rb <
-bash: syntax error near unexpected token `newline'
If you want the shell/console to treat the special characters that it recognizes--as literals, then you have to quote them. There are various ways to quote things in a shell/console:
~/ruby_programs$ ruby 1.rb \;
/[;`'<>-]/
stop word
~/ruby_programs$ ruby 1.rb \<
/[;`'<>-]/
stop word
Note you can use String#[] too:
special = "[;\`'<>-]"
regex = /#{special}/
...
...
if pi[regex]
puts "stop word"
else
puts "incorrect"
end