目前我这样做:
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)
当我查看文件时,它是空的。这有用吗?
答案 0 :(得分:7)
要检查几件事:
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.
我会更像这样编写代码:
bad_links = []
brokenLink = {
:onPage => @lastPage,
:link => @nextPage
}
bad_links << brokenLink
File.write(arrayFilePath + 'badLinks.txt', bad_links.to_json)
这没有经过测试,但它更有意义,而且是惯用的Ruby。