您需要从命令行执行此脚本,而不是文本编辑器,因为系统会提示您输入数字。
这是超紧凑的版本
def validate(n)
if (Float(n) != nil rescue return :invalid)
return :zero if n.to_f == 0
return :valid
end
end
print "Please enter a number: "
puts "#{num = gets.strip} is #{validate(num)}"
输出:
Please enter a number: 00
00 is zero
这是一个较长的版本,您可能可以对其进行扩展以根据您的需要进行调整。
class String
def numeric?
Float(self) != nil rescue false
end
end
def validate(n)
if n.numeric?
return :zero if n.to_f == 0
return :valid
else
return :invalid
end
end
print "Please enter a number: "
puts "#{num = gets.strip} is #{validate(num)}"
这是对所有可能情况的测试
test_cases = [
"33", #int pos
"+33", #int pos
"-33", #int neg
"1.22", #float pos
"-1.22", #float neg
"10e5", #scientific notation
"X", #STRING not numeric
"", #empty string
"0", #zero
"+0", #zero
"-0", #zero
"0.00000", #zero
"+0.00000", #zero
"-0.00000", #zero
"-999999999999999999999995444444444444444444444444444444444444434567890.99", #big num
"-1.2.3", #version number
" 9 ", #trailing spaces
]
puts "\n** Test cases **"
test_cases.each do |n|
puts "#{n} is #{validate(n)}"
end
哪个输出:
Please enter a number: 12.34
12.34 is valid
** Test cases ** 33 is valid
+33 is valid
-33 is valid
1.22 is valid
-1.22 is valid
10e5 is valid
X is invalid
is invalid
0 is zero
+0 is zero
-0 is zero
0.00000 is zero
+0.00000 is zero
-0.00000 is zero
-999999999999999999999995444444444444444444444444444444444444434567890.99 is valid
-1.2.3 is invalid
9 is valid
检查其是否为数字的想法的来源: