4

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?

2
  • 1
    What is badLinksFile and badLinks? A file and an array respectively? Show them in your code please, along with how you open badLinksFile. Commented Feb 20, 2013 at 20:03
  • @theTinMan does that edit make more sense? Commented Feb 20, 2013 at 21:12

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I you helped me before here. This is the same project. I am trying to record a list of URLs visited, Broken links found, URL's found in que to be checked. With my current program I need to read a file at the beginning, and for every 100 links rewrite the set of files.
Cool. Glad I was able to help. I'm curious why you are writing JSON to a file? Generally, when we're dealing with a record of the connections that succeed/fail, we use a database. The schema is up to you, but we can sure help you figure out how to build it. A database is MUCH better than a file on disk for this sort of stuff.
I am open to any suggestions. Point me at a good place to start. The reason I started with json is it seemed simple to use.
mySQL? I have no experience with databases. Can you help me out with a starting point?
Look at Sequel, and experiment with SQLite. It's a good starting point. Both the README and Cheat Sheet are chock-full of information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.