Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: checking if a string can be converted to an integer [duplicate]

Tags:

ruby

Possible Duplicate:
Test if a string is basically an integer in quotes using Ruby?

"1"
"one"

The first string is a number, and I can just say to_i to get an integer.
The second string is also a number, but I can't directly call to_i to get the desired number.

How do I check whether I can successfully convert using to_i or not?

like image 913
MxLDevs Avatar asked May 14 '12 05:05

MxLDevs


People also ask

How do you check if a string is an integer in Ruby?

In Ruby you usually omit the "return" keyword if the return value is generated in the last expression in the function. This will also return an integer value of zero, you probably want a boolean, so something like !!( str =~ /^[-+]?[0-9]+$/) would do that.

How do you convert string to int in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

What checks if an input is numeric in Ruby?

Two ways to determine if a string str represents a Fixnum and if it does, return the Fixnum ; else return nil : 1) Use a regex with anchors: def intify(str); x = str[/^-?\ d+$/]; x ? x. to_i : nil; end .


1 Answers

There's an Integer method that unlike to_i will raise an exception if it can't convert:

>> Integer("1")
=> 1
>> Integer("one")
ArgumentError: invalid value for Integer(): "one"

If you don't want to raise an exception since Ruby 2.6 you can do this:

Integer("one", exception: false)

If your string can be converted you'll get the integer, otherwise nil.

The Integer method is the most comprehensive check I know of in Ruby (e.g. "09" won't convert because the leading zero makes it octal and 9 is an invalid digit). Covering all these cases with regular expressions is going to be a nightmare.

like image 95
Michael Kohl Avatar answered Oct 20 '22 17:10

Michael Kohl