What is a Binding?

In Ruby, objects of the Binding class encapsulate the execution context at a particular place in the code. This context, which includes variables, methods, the value of self, and any associated blocks, can be retained and accessed later.

To keep track of the current scope, Ruby uses binding, which captures the execution context at each line of code.

The binding method returns a Binding object that describes the context at the current line.

2.6.3 :001 > a = 10
 => 10
2.6.3 :002 > binding
 => #<Binding:0x00007fe8270c7698>
2.6.3 :003 > binding.local_variables
 => [:a, :_]
2.6.3 :004 >

Code can be evaluated within a binding using the eval method:

2.6.3 :001 > a = 10
 => 10
2.6.3 :002 > binding.local_variables
 => [:a, :_]
2.6.3 :003 > binding.eval("a")
 => 10
2.6.3 :004 >

An Example of Using Bindings

2.6.3 :001 > class MyTemplateEngine
2.6.3 :002?>   def initialize(template)
2.6.3 :003?>     @template = template
2.6.3 :004?>   end
2.6.3 :005?>
2.6.3 :006?>   def result(binding)
2.6.3 :007?>     @template.gsub(/<%=(.+?)%>/) do
2.6.3 :008 >       binding.eval($1)
2.6.3 :009?>     end
2.6.3 :010?>   end
2.6.3 :011?> end
 => :result
2.6.3 :012 > @title = "My title"
 => "My title"
2.6.3 :014 > description = "I am a description"
 => "I am a description"
2.6.3 :015 > template = MyTemplateEngine.new("<%= @title %> -- <%= description %>")
 => #<MyTemplateEngine:0x00007f8f4b8fbd80 @template="<%= @title %> -- <%= description %>">
2.6.3 :016 > template.result(binding)
 => "My title -- I am a description"

A real-life example of this is how the ERB templating system works in Ruby:

2.6.3 :001 > require 'erb'
 => true
2.6.3 :002 > title = "Sathia"
 => "Sathia"
2.6.3 :003 > ERB.new("Hi <%= title %>").result(binding)
 => "Hi Sathia"

Now that you understand binding, you may have used binding.pry. But what exactly is pry? Read more about it here.