这是另一个解决方案。它不是很像 Ruby,但这是故意的(例如,while
比str.chars.each
这种情况下要快)。
# is a character between 0 and 9? (based on C's isdigit())
def digit?(c)
o = c.ord
o >= 48 && o <= 57 # '0'.ord, '9'.ord
end
# is a string numeric (i.e., represented as an integer or decimal)?
def numeric?(str)
str = str.to_s unless str.is_a?(String)
l = str.length
i = 0
while i < l
c = str[i]
if c == '.' || c == '-'
i += 1
next
end
return false if !digit?(c)
i += 1
end
true
end
这是单元测试。如果我错过了一个案例,请告诉我。对于其他回答者,只需将subject
块更改为您的功能。
if $0 == __FILE__
require 'minitest/autorun'
describe :digit? do
%w(- + : ? ! / \ ! @ $ ^ & *).each do |c|
it "flunks #{c}" do
digit?(c).must_equal false
end
end
%w(0 1 2 3 4 5 6 7 8 9).each do |c|
it "passes #{c}" do
digit?(c).must_equal true
end
end
end
describe :numeric? do
subject { :numeric? }
%w(0 1 9 10 18 123.4567 -1234).each do |str|
it "passes #{str}" do
method(subject).call(str).must_equal true
end
end
%w(-asdf 123.zzz blah).each do |str|
it "flunks #{str}" do
method(subject).call(str).must_equal false
end
end
[-1.03, 123, 200_000].each do |num|
it "passes #{num}" do
method(subject).call(num).must_equal true
end
end
end
end