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
You can use
Integer(str)
and see if it raises:Addendum: It should be pointed out that while this does return true for
"01"
, it does not for"09"
, simply because09
would not be a valid integer literal.Addendum to addendum: Fixed this by changing
Integer(str)
toInteger(str, 10)
, as per @jason-axelson's comment.you can use is_a? method. for eg. 1.is_a? Integer will return true
You can use regular expressions. Here is the function with @janm's suggestions.
An edited version according to comment from @wich:
In case you only need to check positive numbers
Well, here's the easy way:
EDIT: I don't agree with the solutions that provoke an exception to convert the string - exceptions are not control flow, and you might as well do it the right way. That said, my solution above doesn't deal with non-base-10 integers. So here's the way to do with without resorting to exceptions:
I prefer:
config/initializers/string.rb
and then:
or check phone number: