使用JSON将哈希数组写入文件?

时间:2013-02-20 19:54:37

标签: ruby arrays json hashmap

目前我这样做:

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)

当我查看文件时,它是空的。这有用吗?

1 个答案:

答案 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。