atmorell
atmorell

Reputation: 3068

How do I get the second integer in a Ruby string with to_i?

I need to convert some strings, and pull out the two first integers e.g:

unkowntext60moreunknowntext25something

To:

@width = 60
@height = 25

If I do string.to_i, I get the first integer:, 60. I can't figure out how I get the second integer, 25. Any ideas?

Upvotes: 2

Views: 1045

Answers (3)

molf
molf

Reputation: 74945

How about something like:

text = "unkowntext60moreunknowntext25something"
@width, @height = text.scan(/\d+/).map { |n| n.to_i }  #=> 60, 25

Upvotes: 11

Simone Carletti
Simone Carletti

Reputation: 176382

@width, @height = "unkowntext60moreunknowntext25something".scan(/[0-9]+/)

Upvotes: 4

Andrew Hare
Andrew Hare

Reputation: 351506

You can use a regular expression like (\d+) to capture all numbers in the string and then iterate the capture groups converting each one to an integer.

Edit: I don't know Ruby so I've wiki'd this answer in hopes that a Rubyist would flesh out a code example.

Upvotes: 2

Related Questions