tags:

views:

238

answers:

3

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?

+2  A: 

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.

Andrew Hare
+4  A: 
@width, @height = "unkowntext60moreunknowntext25something".scan(/[0-9]+/)
Simone Carletti
this returns strings, not integers
Mario Menger
That's true, you can easily cast them to int using to_i but something it's just fine to keep them as string (if the receiver doesn't need to get integers or it casts them again to string. this is a common case if you use @width and @height in a Rals helper).
Simone Carletti
+10  A: 

How about something like:

text = "unkowntext60moreunknowntext25something"
@width, @height = text.scan(/\d+/).map { |n| n.to_i }  #=> 60, 25
molf
Perfect! This was exactly what I was looking for :)
atmorell