Introduction to Bindings

The Pixaxe book defines Binding objects to:

encapsulate the execution context at some particular place in the code and retain this context for future use.

You can get a Binding for the current context by calling Kernel#binding.

The Binding stores information about the variables, methods, and self and you can access them by passing the Binding to eval.

You can see here that @title gets evaluated differently depending on the binding. The first eval returns "nice and shiny" because that is the value of @title for the first Product p.

Blocks and Procs

Blocks carry information about their Binding.

Notice here that a is "inside a" and not "resetting a". This is beacuse a block stores the variables as they were originally defined. The a in try_to_set_a does not interfere with the a in a_block.

An interesting note is that you can redefine variable within a Binding.

This is because the Binding in this case is the top-level binding which happens to be the same binding in which a was defined in originally.

Practical Use

Bindings are often used when evaluating ERB. (For those of you who don’t know, ERB is a template system that is included in the Ruby Standard Library.)

ERB#result takes a Binding object as its argument and the variables in the ERB template are evaluated in this context.

Going back to our Product example from earlier, lets see how we can use the Product’s bindings in this fashon:

Conclusion

As you can see Binding is a very handy object but this article serves as only an introduction to the subject. Here are a couple articles that deal with binding a little more in-depth.

Jim Weirich’s Variable Bindings in Ruby

Pick Axe page on Binding

Share this post: These icons link to social bookmarking sites where readers can share and discover new web pages.

  • Digg
  • del.icio.us
  • Reddit
  • Technorati

About this entry