目前我正在这样做:

badLinks = Array.new
badLinksFile = File.new(arrayFilePath + 'badLinks.txt', 'w+')
badLinksFile.puts badLinks.to_json

数组 badLinks 包含散列并且是:
brokenLink = Hash.new
brokenLink[:onPage] = @lastPage
brokenLink[:link] = @nextPage
badLinks.push(brokenLink)

当我查看文件时,它是空的。这应该工作吗?

最佳答案

需要检查的几件事:

badLinksFile = File.new(arrayFilePath + 'badLinks.txt', 'w+')

应该是 'w' 而不是“w+”。从 IO 文档:
  "w"  |  Write-only, truncates existing file
       |  to zero length or creates a new file for writing.
  -----+--------------------------------------------------------
  "w+" |  Read-write, truncates existing file to zero length
       |  or creates a new file for reading and writing.

I'd write the code more like this:

bad_links = []

brokenLink = {
  :onPage => @lastPage,
  :link => @nextPage
}

bad_links << brokenLink

File.write(arrayFilePath + 'badLinks.txt', bad_links.to_json)

这没有经过测试,但它更有意义,并且是惯用的 Ruby。

10-08 04:36