Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
Shpigford Avatar asked Feb 08 '10 20:02

Shpigford


People also ask

How do you check if a string contains at least one number?

To check if a string contains at least one number using regex, you can use the \d regular expression character class in JavaScript. The \d character class is the simplest way to match numbers.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.


5 Answers

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
like image 58
Ethan Avatar answered Oct 02 '22 17:10

Ethan


Alternatively, without using a regex:

def has_digits?(str)
  str.count("0-9") > 0
end
like image 22
glenn jackman Avatar answered Oct 02 '22 18:10

glenn jackman


if /\d/.match( theStringImChecking ) then
   #yep, there's a number in the string
end
like image 27
Jacob Mattison Avatar answered Oct 02 '22 19:10

Jacob Mattison


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.

like image 44
the Tin Man Avatar answered Oct 02 '22 18:10

the Tin Man


!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
like image 34
Shreyas Avatar answered Oct 02 '22 18:10

Shreyas