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
One liner in
string.rb
is_
. I find that silly on questionmark methods, I like"04".integer?
a lot better than"foo".is_integer?
."01"
and such.For more generalised cases (including numbers with decimal point), you can try the following method:
You can test this method in an irb session:
For a detailed explanation of the regex involved here, check out this blog article :)
Expanding on @rado's answer above one could also use a ternary statement to force the return of true or false booleans without the use of double bangs. Granted, the double logical negation version is more terse, but probably harder to read for newcomers (like me).
personally I like the exception approach although I would make it a little terser.
However as others have already stated this doesn't work with Octal strings...