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?
There is no direct equivalent in Ruby. The two main options are:
Integer('42')
. This is more like C#'s Int32.Parse
, in that it will raise an Error.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.Integer(str) is probably the thing you need - Integer('123')
will return 123 and Integer('123a')
will throw exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With