Zach
Zach

Reputation: 895

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

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?

Upvotes: 4

Views: 2377

Answers (1)

the Tin Man
the Tin Man

Reputation: 160551

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.

Upvotes: 7

Related Questions