为什么我在此代码中收到"not a number"错误?



我只是希望有人能帮我解决这个代码:

def write(aFile, number)
index = 1
while (index < number)
aFile.puts(index.to_s)
index += 1
end
end
def read(aFile)
count = aFile.gets
if (is_numeric?(count))
count = count.to_i
else
count = 0
puts "Error: first line of file is not a number"
end
index = 0
while (count < index)
line = aFile.gets
puts "Line read: " + line
end
end
# Write data to a file then read it in and print it out
def main
aFile = File.new("mydata.txt", "w") 
if aFile  
write(aFile, 11)
aFile.close
else
puts "Unable to open file to write!"
end
aFile = File.new("mydata.txt", "r") 
if aFile
read(aFile)
aFile.close
else
puts "Unable to open file to read!"
end
end
# returns true if a string contains only digits
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main

我试图得到的结果是:

Line read: 0
Line read: 1
...
Line read: 10

但我得到了:

Error: first line of file is not a number

为什么会出现这种情况?我的代码一定有问题。

def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end

代码块(如方法体(的结果是在其中计算的最后一个表达式。您的true将成为if的值,并被忽略,因为计算的下一个表达式是false,它总是返回的。有几种方法可以改善这一点。

def is_numeric?(obj)
return true if /[^0-9]/.match(obj).nil?
false
end
def is_numeric?(obj)
/[^0-9]/.match(obj).nil?
end
def is_numeric?(obj)
/[^0-9]/ !~ obj
end
def is_numeric?(obj)
Integer(obj) rescue false
end

还有更多。

相关内容

最新更新