Of course, Regexp is good for this:
string = "123abcd" /^(?<num>\d+)$/ =~ string num # => nil string = "123" /^(?<num>\d+)$/ =~ string num # => '123' # String
So, if you need to check the condition:
if /^(?<num>\d+)$/ =~ string num.to_i
#to_i String method is not valid for your case, because it will return a number if the string is even with letters:
string = "123abcd" string.to_i # 123
Mal Skrylev
source share