Eth*_*han 36
您可以使用String
类的=~
方法和正则表达式/\d/
作为参数.
这是一个例子:
s = 'abc123'
if s =~ /\d/ # Calling String's =~ method.
puts "The String #{s} has a number in it."
else
puts "The String #{s} does not have a number in it."
end
Run Code Online (Sandbox Code Playgroud)
或者,不使用正则表达式:
def has_digits?(str)
str.count("0-9") > 0
end
Run Code Online (Sandbox Code Playgroud)
if /\d/.match( theStringImChecking ) then
#yep, there's a number in the string
end
Run Code Online (Sandbox Code Playgroud)