I need a function, is_an_integer, where
"12".is_an_integer? returns true
"blah".is_an_integer? returns false
how can i do this in ruby? i would write a regex but im assuming there is a helper for this that i am not aware of
I need a function, is_an_integer, where
"12".is_an_integer? returns true
"blah".is_an_integer? returns false
how can i do this in ruby? i would write a regex but im assuming there is a helper for this that i am not aware of
The Best and Simple way is using
Float
Integer
is also good but it will return0
forInteger nil
A much simpler way could be
Might not be suitable for all cases but a simple
might also do for some.
So if it's a number and not 0 it will return a number. If it returns 0 it's either a word string or 0.
Although explicit use of the case equality operator should be avoided,
Regexp#===
looks very clean here:You can do a one liner:
or even
Depending on what you are trying to do you can also directly use a begin end block with rescue clause:
Solution:
Explanation:
/^(\d)+$/
is regex expression for finding digits in any string. You can test your regex expressions and results at http://rubular.com/.IntegerRegex
to avoid unnecessary memory allocation everytime we use it in the method.integer?
is an interrogative method which should returntrue
orfalse
.match
is a method on string which matches the occurrences as per the given regex expression in argument and return the matched values ornil
.!!
converts the result ofmatch
method into equivalent boolean.String
class is monkey patching, which doesn't change anything in existing String functionalities, but just adds another method namedinteger?
on any String object.