目前我正在这样做:
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。
关于ruby - 使用 JSON 将哈希数组写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988742/