views:

282

answers:

5

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?

A: 

use the Regex /\d/

Mike Warner
I think to be a truly useful answer you need to actually supply some code in Ruby, since that is what was asked. Don't go for the quick, easy answer. Instead, try to add some value to your answer by giving working code and/or clear explanations and/or links to documentation.
Bryan Oakley
+2  A: 
if /\d/.match( theStringImChecking ) then
   #yep, there's a number in the string
end
JacobM
+8  A: 

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
Ethan
A: 

Alternatively, without using a regex:

def has_digits?(str)
  str.count("0-9") > 0
end
glenn jackman
that's probably less efficient, if you ignore the overhead of compiling the regular expression (which is fair if the test is being done in a large loop or the string to check is very long). For a degenerative case, your solution must traverse the entire string whereas a proper regular expression will stop as soon as a digit is found.
Bryan Oakley
A: 

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.

Greg