Cristian M
Cristian M

Reputation: 357

How can I convert an array of numbers into a whole number?

I am working on a procedure that retrieves the numbers from some elements that can be found in a select list. For example from "test element (100)" i am trying to get the number "100". I used this code to do it, it catches the number between the the two parentheses:

            before = Regexp.escape '('
            after = Regexp.escape ')'
            x = "test element (100)"[-5, 5].scan(/#{before}(.*?)#{after}/).flatten

This code works and the value for X will be 100. But this "100" is in fact an array.

Does some body know how can I convert array "100" into the integer "100"?

Thank you.

Upvotes: 0

Views: 130

Answers (3)

Kyle
Kyle

Reputation: 22258

Why not this?

x = "test element (100)"[/(?<=\()\d+(?=\))/].to_i # 100

Example:

1.9.3-p194 :001 > "test element (100)"[/(?<=\()\d+(?=\))/].to_i
 => 100
1.9.3-p194 :002 > "test (250) other stuff"[/(?<=\()\d+(?=\))/].to_i
 => 250 

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

Why don't you use:

"test element (100)"[/\d+/]

which returns:

"100"

If you want the integer value, use:

"test element (100)"[/\d+/].to_i

Upvotes: 1

ddb
ddb

Reputation: 1406

x.first

should give it to you.

Upvotes: 0

Related Questions