0

I need to somehow read an integer within a string. The string will be as follows;

GAME_SWITCH(476)

And I need to read the 476 part. Note, it won't be 476 each time, but it will be "GAME_SWITCH(...)" each time. I've tried using the .delete methods to delete "GAME_SWITCH(" and ")", but that has no effect for some reason. I just want the "476" which I can then convert to an integer.

Furthermore, is there also a way to check if the string adheres to those rules? if the string is just "foobar" it returns false?

I am using Ruby 1.8.1

Thanks a lot!

HarryE
  • 17
  • 5

2 Answers2

0

You can solve the problem with regular expressions for example:

if m = str.match(/^GAME_SWITCH\((\d+)\)$/)
  m[1].to_i
else
  false
end
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
  • Hey, this worked! In order to convert to an integer properly, though, I had to use another variable, like int = str[1].to_i Thanks! – HarryE Mar 16 '12 at 20:01
0

Try something like this

my_string.scan(/\d+/)[0].to_i
Marlon León
  • 171
  • 13