What is equivalent to C # int.TryParse () method in Ruby?

Possible duplicate:
Safe One-Piece Parsing in Ruby

int.Parse converts the string to an integer, but throws an exception if the string cannot be converted. int.TryParse does not int.TryParse error when it cannot convert sting to int, but returns 0 and bool , which say whether the string can be converted.

Is there something similar in Ruby?

+7
source share
2 answers

There is no direct equivalent in Ruby. Two main options:

  • Use Integer('42') . This is more like C # Int32.Parse as it causes an error.
  • Use String.to_i , that is: "42".to_i . This will return 0 if you pass something that at least partially does not convert to an integer but never causes an error. (Provided that you also did not provide an invalid base.) The integer part of the string will be returned, or 0 if the integer does not exist in the string.
+7
source

The integer (str) is probably Integer('123') you need - Integer('123') will return 123, and Integer('123a') throw an exception.

+1
source

All Articles