Getting my Ruby file to load into Pry?

Nick Res picture Nick Res · Dec 29, 2013 · Viewed 12.5k times · Source

I'm trying to edit my Ruby file with Pry. There are few variables that are set in it, and for whatever reason I can't seem to cd into them because they aren't being defined even after I 'load' the file.

Here is the code:

require 'nokogiri'
require 'open-uri'

doc = Nokogiri.XML('<foo><bar /><foo>', nil, 'UTF-8') 

url = "http://superbook.eventmarketer.com/category/agencies/" 

puts "Finished!"

In Pry I do:

load "./AgencyListingScraper.rb"

and then this is the output:

7] pry(main)> load './AgencyListingScraper.rb'
Finished!
=> true
[8] pry(main)> 

Then when I try to do something like:

[8] pry(main)> url
NameError: undefined local variable or method `url' for main:Object
from (pry):6:in `__pry__'
[9] pry(main)> cd url
Error: Bad object path: url. Failed trying to resolve: url. #<NameError: undefined local     
variable or method `url' for main:Object>
[10] pry(main)> 

This is what I get.

I think I'm not loading the file correctly although I've been searching for hours and I can't figure out how to properly do this. I was doing it right months ago when I had made a scraper with Ruby, but this time I'm having trouble just getting started because of this bit.

Thanks for your help in advance!

Answer

JaTo picture JaTo · Dec 29, 2013

Try it this way:

In your file include Pry and do a binding.pry:

require 'nokogiri'
require 'open-uri'
require 'pry'

doc = Nokogiri.XML('<foo><bar /><foo>', nil, 'UTF-8') 

url = "http://superbook.eventmarketer.com/category/agencies/" 

binding.pry
puts "Finished!"

Then run the file by executing:

ruby AgencyListingScraper.rb 

That should drop you into a Pry session where you can use commands like ls to see all of the variables.

Both the way you used Pry, and this way, work. However, the reason that load may not be working in your case is that local variables don't get carried over across files, like when you require one file from another.

Try loading this file:

#test.rb
y = "i dont get carried over cause i am a local variable"
b= "i dont get carried over cause i am a local variable"
AAA= "i am a constant so i carry over"
@per = "i am an instance var so i get carried over as well"

When you load it in Pry using load "test.rb" you can see that you can't get access to the local variables from that file.