为什么在此代码中出现“ not a number”错误?

时间:2019-11-06 16:50:11

标签: ruby file debugging

我只是希望有人可以提供以下代码来帮助我:

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

为什么会这样?我的代码一定有问题。

1 个答案:

答案 0 :(得分:5)

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

还有更多