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