Stefano Crocco
11/19/2006 10:17:00 PM
Alle 22:21, domenica 19 novembre 2006, Luca Scaljery ha scritto:
> Hi All
>
> I just tried to test the content of a string, something like this:
>
>
> c = "1234AA"
>
> if c.scan( /1234567890/ )
> p "OK"
> else
> p "NO"
> end
>
>
> This always returns "OK" :(
>
> Any suggestions what goes wrong here. And is this the way to check the
> content of a string ?
>
> Thanks a lot
> LuCa
Even when there's no match, String#scan returns an array, so your is always
true. To make it work, you should use
if !c.scan(/1234567890/).empty?
As for your second question, it depends on what exactly you want to do. It is
the correct form if you need to get all the numbers in the string, regardless
of their position or any other thing (by the way, if you want to match a
digit in a regexp, you can use /\d/). If you simply want to check whether the
string contains a digit, you can use String#match or =~ with the /\d/ regexp.
If you need more control on the scanning, you can use the StringScanner
class.
I hope this helps
Stefano