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

Wah*_*h.P 0 ruby debugging file

我只是希望有人可以通过以下代码帮助我:

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
Run Code Online (Sandbox Code Playgroud)

我想要得到的结果是这样的:

Line read: 0

Line read: 1

...

Line read: 10
Run Code Online (Sandbox Code Playgroud)

但我得到:

Error: first line of file is not a number
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*sev 5

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

代码块(例如方法主体)的结果是其中的最后一个表达式。您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
Run Code Online (Sandbox Code Playgroud)

还有很多。

  • @ Wah.P如果提供的字符串的一个字符不是数字,则使用正则表达式`/ [^ 0-9] /`进行匹配。gets返回末尾包含换行符char的行(不是数字),从而使语句始终为false。要解决此问题,您可以使用[`chomp`](https://ruby-doc.org/core-2.6.5/String.html#method-i-chomp)截断尾随换行符。(我会使用`!obj.match?(/ \ D /)`) (2认同)