Click to See Complete Forum and Search --> : Ruby: Get int from Part of String


nko
03-03-2006, 05:33 PM
I've got a Ruby script. In my script, there is a string. In my string, there are letters, followed by a number followed by more letters. For example:

"line1ID"

-or-

"line33Name"

I'm trying to distill the number from within the string. I've gone through all the regexping and string-methoding I can find in any documentation and can't figure out an elegant way of turning that embedded integer in to a... well, and integer!

There are all kinds of elegant ways to solve all sorts of elegant problems in Ruby, so I can't believe that I'm going to have to define a function that performs voodoo on my strings to distill integers.

How do I get that number out of that string?

truls
03-03-2006, 08:09 PM
myint = mystring.scan(/\d*/)

I think myint will be an array, so you will just have to pick the first element.

nko
03-03-2006, 08:26 PM
Excellent! My resulting code is a little ugly as myint does turn out to be an Array, but this is MUCH more workable than what I was thinking. Thanks!

truls
03-04-2006, 05:55 PM
Correction:

One little thing. The pattern should be:
/\d+/
to ensure that you get at least one digit. This ensures that the first element of the array is an integer.

+ means at least one digit
* means zero or more