本文介绍了使用JSON写哈希数组到一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我这样做:

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)

当我看一下这个文件是空的。如果这一工作?

When I look at the file it is empty. Should this work?

推荐答案

几件事情要检查:

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.

我会写的code更是这样的:

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.

这篇关于使用JSON写哈希数组到一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:56