Debugging: What is binding in Ruby?

You might have thought always whenever you wrote code binding.pry in your application to debug your application.

People often say “do binding to see whats going on”. Actually you are not doing binding but prying into the binding. So, its good to say “Please pry into that binding”.

But, what is binding in the first place?

Lets see an example before we explain the term binding

def binding1
  occupation = 'doctor'
  binding # returns that particular binding/context
end

def binding2
  occupation = 'engineer'
  binding
end

erb = "Chabi is <%= occupation %>"
ERB.new(erb).result(binding1)
# => "Chabi is doctor"
ERB.new(erb).result(binding2)
# => "Chabi is engineer"

Looking into the example, some of you might have gotten the idea that binding is nothing more than an object representing a closure where variables/objects are defined.

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. You can also imagine this as a variable representing container where stuffs are defined.

Example:

class Demo
  def initialize(n)
    @secret = n
  end

  def get_binding
    return binding()
  end
end

k1 = Demo.new(99)
b1 = k1.get_binding
k2 = Demo.new(-3)
b2 = k2.get_binding

eval("@secret", b1)   #=> 99
eval("@secret", b2)   #=> -3
eval("@secret")       #=> nil

 

For more info see this

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s