Using JSON to write an array of hashes to a file?

巧了我就是萌 提交于 2019-12-23 12:14:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!