# Understanding the Concept of Binding in Ruby

*Published on July 08, 2023*

---


After I published the post on&nbsp;[rendering dynamic views with ERB](/render-dynamic-views-using-erb), I got a bunch of emails from readers asking about the binding, as many had not seen or used it before. To be honest, I haven't used it in my typical Rails apps, too. However, it's a very interesting concept to learn about and very useful if you're working with view templates. So in this article, we'll learn about binding in Ruby.

## What is Binding?

A Ruby binding is an instance of the&nbsp;`Binding`&nbsp;class. It's an object that packages or encapsulates the current scope, allowing you to pass it around in your code.

> Objects of class&nbsp;[`Binding`](https://docs.ruby-lang.org/en/3.2/Binding.html)&nbsp;encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, and value of&nbsp;`self`&nbsp;that can be accessed in this context are all retained.&nbsp;[`Binding`](https://docs.ruby-lang.org/en/3.2/Binding.html)&nbsp;objects can be created using&nbsp;[`Kernel#binding`](https://docs.ruby-lang.org/en/3.2/Kernel.html#method-i-binding). -&nbsp;[Ruby Docs](https://docs.ruby-lang.org/en/3.2/Binding.html)

The&nbsp;[`Kernel#binding`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-binding)&nbsp;method returns the current binding object. Think of this binding object as a wrapper that encapsulates the current programming environment, i.e. variables, methods, and even the&nbsp;`self`&nbsp;object.

**The basic idea behind binding is to store the current context in an object for later use. Later, you can execute some code in the context of that binding, using**&nbsp;**`eval`****.**

The most common and realistic use case for a binding object is to use it later to fill some pre-defined slots in a template, like ERB views. So you save the current context including variables in a binding, and use it somewhere else to generate the final views, just like Rails.

## Evaluating Ruby Code in Different Context

The&nbsp;`Kernel#eval`&nbsp;method takes a string that contains Ruby code, executes it, and returns the result.

```ruby
eval %q(
  def run(task)
    puts "running task: #{task}"
  end
)

run "compile"  # running task: compile
```

However, you can pass a binding object as the second argument of the&nbsp;`Kernel#eval`&nbsp;method. This establishes the environment for the evaluation.

```ruby
def get_binding(word)
  return binding  # calls Kernel#binding method
end

word = "Ruby"
eval "puts 'hello ' + word"  # hello Ruby
eval "puts 'hello ' + word", get_binding("Rails")  # hello Rails
```

The following example illustrates how&nbsp;`eval`&nbsp;returns a different value for the&nbsp;`language`&nbsp;variable for different bindings.

```ruby
language = "JavaScript"

eval("puts language", binding)  # JavaScript

def get_binding
  language = "C-Sharp"
  binding
end

new_binding = get_binding
eval("puts language", new_binding)  # C-Sharp

class Ruby
  def get_binding
    language = "Ruby"
    binding
  end
end

ruby_binding = Ruby.new.get_binding
eval("puts language", ruby_binding)  # Ruby
```

If you check out the source code of the&nbsp;[IRB](https://github.com/ruby/irb)&nbsp;gem, you'll notice that it makes abundant use of the bindings.

## Top-Level Binding

Ruby provides a constant called&nbsp;`TOPLEVEL_BINDING`&nbsp;that returns the binding of the top-level scope. Use it to access the top-level scope from anywhere in the program.

```ruby
def run_ruby
  puts "running inside main"
end

class Ruby
  def run_ruby
    puts "running inside Ruby"
  end

  def exec
    eval "run_ruby", binding  # running inside Ruby
    eval "run_ruby", TOPLEVEL_BINDING  # running inside main
  end
end

Ruby.new.exec
```

## How ERB Uses Binding

The following code substitutes variables into a template string with erb. It uses&nbsp;`Kernel#binding`&nbsp;method to get the current context.

```ruby
require 'erb'

name = 'Akshay'
age = 30

erb = ERB.new 'My name is <%= name %> and I am <%= age %> years old'
puts erb.result(binding)

# Output:
#
# "My name is Akshay and I am 30 years old"
```

> Note the&nbsp;`<%= title %>`&nbsp;statement. Within an erb template, Ruby code can be included using both&nbsp;`<% %>`&nbsp;and&nbsp;`<%= %>`&nbsp;tags.  
>   
> The&nbsp;`<% %>`&nbsp;tags are used to execute Ruby code that does not return anything, such as conditions, loops, or blocks, and the&nbsp;`<%= %>`&nbsp;tags are used when you want to output the result.

**What's going on in the above example?**

1. After requiring the&nbsp;`ERB`&nbsp;gem and creating a few variables, we create an instance of the&nbsp;`ERB`&nbsp;class with a template string.
2. We create a&nbsp;`Binding`&nbsp;object by calling the&nbsp;[`Kernel#binding`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-binding)&nbsp;method. Again, think of the binding object as a wrapper that includes the current programming environment with variables like&nbsp;`name`&nbsp;and&nbsp;`age`, methods, and even the&nbsp;`self`&nbsp;object.
3. The&nbsp;`result`&nbsp;method on the&nbsp;`erb`&nbsp;object uses this binding object and the variables defined in that binding to replace the slots in the template string, generating the final string printed above.

Now go ahead and re-read the previous post on rendering dynamic views. It will make more sense this time.

[Let’s Build a Webapp in Ruby without Rails: Serve Static Files and Render Dynamic Views](/render-dynamic-views-using-erb)

