I'd suggest another way of doing it. Also, because you asked "positive" integer, I made two separate methods for positive integer and non-negative integer.
class String
def numeric?
!self.match(/[^0-9]/)
end
def positive_integer?
self.to_i > 0
end
def nonnegative_integer?
self.to_i > 0 or self == '0'
end
end
Here's the benchmark code:
require 'benchmark'
include Benchmark
bmbm(100) do |x|
x.report('numeric?') do
"some invalid string".numeric?
end
x.report('positive_integer?') do
"some invalid string".positive_integer?
end
x.report('nonnegative_integer?') do
"some invalid string".nonnegative_integer?
end
end
Result:
numeric?
0.000000 0.000000 0.000000 ( 0.000045)
positive_integer?
0.000000 0.000000 0.000000 ( 0.000012)
nonnegative_integer?
0.000000 0.000000 0.000000 ( 0.000015)
It seems like positive_integer? and nonnegative_integer? are faster in this micro-benchmark.
Finally, as a side note, you can define integer? method in a similar fashion:
class String
def integer?
self.to_i.to_s == self
end
end
{1,1}multiplier? By default all character classes and literals are matched exactly once unless otherwise specified. This is redundant.