What's the equivalent of C#'s int.TryParse() method in Ruby?

c#, ruby

Solution

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

- Use `Integer('42')`. This is more like C#'s `Int32.Parse`, in that it will raise an Error.

- 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.

Problem

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?

Original source

Related problems