Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`binding.pry` vs `pry`

Tags:

ruby

pry

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?

like image 904
Francio Rodrigues Avatar asked Jun 27 '26 02:06

Francio Rodrigues


1 Answers

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).

like image 93
max pleaner Avatar answered Jun 28 '26 18:06

max pleaner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!