10

Possible Duplicate:
Safe integer parsing in Ruby

int.Parse converts a string into an integer, but throws an exception if the string cannot be convert. int.TryParse doesn't throw an error when it can't convert the sting to an int, but rather returns 0 and a bool that says whether the string can be converted.

Is there something similar in Ruby?

Community
  • 1
  • 1
Richard77
  • 20,343
  • 46
  • 150
  • 252

2 Answers2

10

There is no direct equivalent in Ruby. The two main options are:

  1. Use Integer('42'). This is more like C#'s Int32.Parse, in that it will raise an Error.
  2. Use String.to_i, ie: "42".to_i. This will return 0 if you pass in something which isn't at least partly convertible to an integer, but never cause an Error. (Provided you don't also provide an invalid base.) The integer portion of the string will be returned, or 0 if no integer exists within the string.
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 2 - wrong, it'll not always return 0 on wrong numbers. – iced Sep 20 '12 at 22:16
  • @iced As long as base is valid, "If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid." [from linked documentation] Basically, if you leave off base, as I showed, you'll get an integer from the string, or 0. – Reed Copsey Sep 20 '12 at 22:20
  • Still, `'123a'.to_i` returns 123, not 0. I don't think '123a' is valid number in 10-base space. If official docs say what you quoted it's error in docs which should be reported. – iced Sep 20 '12 at 22:22
  • How about if I have something like "abc".to_i what do I get? – Richard77 Sep 20 '12 at 22:25
  • @Richard77 You'd get `0` if you use `"abc".to_i` – Reed Copsey Sep 20 '12 at 22:25
  • basic algo of to_i is smth like `result = 0; while there_are_more_digits; result = result * 10 + next_digit; end` – iced Sep 20 '12 at 22:27
1

Integer(str) is probably the thing you need - Integer('123') will return 123 and Integer('123a') will throw exception.

iced
  • 1,562
  • 8
  • 10
  • Sounds like the OP wants a method that *won't* throw an exception on parse failure, though. – Dan J Sep 20 '12 at 22:09
  • @Dan J, you are right. I don't know yet how to handle exceptions in ruby so a method that doesn't throw an error would be much helpful – Richard77 Sep 20 '12 at 22:11
  • Handling exceptions is easy - begin / rescue. Other ways is just str.to_i, but it'll parse as much of string as it can, so both `'123'.to_i` and `'123a'.to_i` will return 123. – iced Sep 20 '12 at 22:13