Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ruby

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?

like image 839
Richard77 Avatar asked Sep 20 '12 22:09

Richard77


2 Answers

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.
like image 188
Reed Copsey Avatar answered Oct 17 '22 02:10

Reed Copsey


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

like image 39
iced Avatar answered Oct 17 '22 03:10

iced