ruby-on-railsrubyanemone

Writing the output of loop into a text file from a Ruby web crawler gem


I'm a complete Ruby noob, currently going through the Treehouse tutorials but I need some quick help for outputting the content of an Anemone crawl into a text file for my job(I'm an SEO). How do I get the following to dump it's output into a text file?

require 'anemone'

Anemone.crawl("http://www.example.com/") do |anemone|
 anemone.on_every_page do |page|
   puts page.url
 end
end

Help is much appreciated!


Solution

  • You can puts to a file handle, almost the same as if it was STDOUT. A very simple adjustment to your code is to add a File.open block:

    require 'anemone'
    
    File.open('report.txt', 'w') do |file|
    
      Anemone.crawl("http://www.example.com/") do |anemone|
       anemone.on_every_page do |page|
         file.puts page.url
       end
      end
    
    end