The binding method in ruby

I stumbled upon the binding method in Ruby.

Try Binding.new and it'll throw an error. It seems that the only way you can get an instance of the Binding class is by calling the binding method. I'm sure this method calls the Object.binding method either directly or indirectly. Try Object.binding and i'll say that its a private method.

So what's binding?

binding contains the scope of the current ruby block and allows accessing stuff that would else not be in scope. For example,

And you get a NameError. (I love the errors in Ruby. They are well named and are a pleasure to read.)

Modify the say method to accept an argument. Change the puts to eval a ruby expression and pass the binding as second argument to it. When the binding instance is passed, eval evaluates the expression in the scope of the binding.

Now try passing the scope to the say method and see how msg is accessed by magic

Posted
Views
Filed under: