问题
Currently I am doing this:
badLinks = Array.new
badLinksFile = File.new(arrayFilePath + 'badLinks.txt', 'w+')
badLinksFile.puts badLinks.to_json
The array badLinks contains the hashes and is:
brokenLink = Hash.new
brokenLink[:onPage] = @lastPage
brokenLink[:link] = @nextPage
badLinks.push(brokenLink)
When I look at the file it is empty. Should this work?
回答1:
A couple things to check:
badLinksFile = File.new(arrayFilePath + 'badLinks.txt', 'w+')
should probably be 'w' instead of 'w+'. From the IO documentation:
"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)
That's not tested, but it makes more sense, and is idiomatic Ruby.
来源:https://stackoverflow.com/questions/14988742/using-json-to-write-an-array-of-hashes-to-a-file