What is the difference between calling pry
and binding.pry
? For example:
require 'pry'
class Bookshop
def initialize(book)
@books = []
@hp = 'harry potter'
lotr = 'lord of the rings'
@books << @harry_potter
@books << lord_of_the_rings
@books << book
binding.pry #OR pry
end
def print_all_books
puts @books.join(', ')
end
end
new_bookshop = Bookshop.new('the hobbit')
binding.pry
gives me access to instance variable @hp
, local variables lotr
, and instance method print_all_books
.pry
gives access to instance variables and methods, but throws a NameError: undefined local variable
for lotr
.Both indicate the same context. what is going on here? Is there a case in which calling pry
over binding.pry
is desirable?
Re-iterating what I said in comments.
If you look at the source for the method (http://www.rubydoc.info/github/pry/pry/Object), it is patched on Object which means you can call it on basically anything. Whatever you call it on becomes the value of self
in the ensuing REPL. pry
, self.pry
, and Pry.start(self)
all do the same thing.
binding
is kind of a magic/complicated thing which captures the 'context' at a certain place, and makes those local variables accessible from elsewhere. By using binding.pry
or Pry.start(binding)
you ensure the local variables are in scope for the REPL (how, exactly, I can't say).
You also see binding
used in other places where you want to reference local variables in some other scope. For example to evaluate a string of ERB you can use ERB.new(string).result(binding)
.