How do I check if a string has at least one number in it using Ruby?

寵の児 提交于 2019-12-30 07:58:13

问题


I need to check to see if a string contains at least one number in it using Ruby (and I assume some sort of regex?).

How would I do that?


回答1:


You can use the String class's =~ method with the regex /\d/ as the argument.

Here's an example:

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



回答2:


Alternatively, without using a regex:

def has_digits?(str)
  str.count("0-9") > 0
end



回答3:


if /\d/.match( theStringImChecking ) then
   #yep, there's a number in the string
end



回答4:


Rather than use something like "s =~ /\d/", I go for the shorter s[/\d/] which returns nil for a miss (AKA false in a conditional test) or the index of the hit (AKA true in a conditional test). If you need the actual value use s[/(\d)/, 1]

It should all work out the same and is largely a programmer's choice.




回答5:


!s[/\d/].nil?

Can be a standalone function -

def has_digits?(s)
  return !s[/\d/].nil?
end

or ... adding it to the String class makes it even more convenient -

class String
  def has_digits?
    return !self[/\d/].nil?
  end
end


来源:https://stackoverflow.com/questions/2224790/how-do-i-check-if-a-string-has-at-least-one-number-in-it-using-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!