2

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?

Jim Puls
  • 79,175
  • 10
  • 73
  • 78
atmorell
  • 3,052
  • 6
  • 30
  • 44

3 Answers3

12

How about something like:

text = "unkowntext60moreunknowntext25something"
@width, @height = text.scan(/\d+/).map { |n| n.to_i }  #=> 60, 25
molf
  • 73,644
  • 13
  • 135
  • 118
4
@width, @height = "unkowntext60moreunknowntext25something".scan(/[0-9]+/)
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • this returns strings, not integers – Mario Menger Jun 29 '09 at 20:40
  • 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 Jun 29 '09 at 20:47
2

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
  • 344,730
  • 71
  • 640
  • 635