How can I test whether a Ruby string contains only a specific set of characters?
For example, if my set of allowed characters is \"AGHTM\"
plus digits <
A nicely idiomatic non-regex solution is to use String#count:
"MT3G22AH".count("^AGHTM0-9").zero? # => true
"TAR34".count("^AGHTM0-9").zero? # => false
The inverse also works, if you find it more readable:
"MT3G22AH".count('AGHTM0-9') == "MT3G22AH".size # => true
Take your pick.
For longer strings, both methods here perform significantly better than regex-based options.