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

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?


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."
  puts "The String #{s} does not have a number in it."

Alternatively, without using a regex:

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

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

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.


Can be a standalone function -

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

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

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


 ? check if string contains both number and letter (at least)
 ? Check if string contains at least one of each: lowercase letter, uppercase letter, number, and special character
 ? Randomize letter color in javascript
 ? Identifying Number in String Using For Loops
 ? Match the end half of an expersion to only letters SQL ORACLE
 ? Find a substitution that sorts the list
 ? Letter visualisation in TilePane in JavaFX
 ? Java Random Class that Outputs Letters (A to E)
 ? Expression of italics and superscripts in ggpot axis title
 ? Count multiple characters in a string separately