Sunday, February 17, 2008

binding in ruby

This is what 'The Ruby Way' (Section 11.3.1) says about the 'binding':
You can encapsulate the current binding in an object using the method Kernel#binding. Having done that, you can pass the binding as the second parameter to eval, setting the execution context for the code being evaluated.

def some_ethod
a = "local variable"
return binding

the_binding = some_method
eval "a", the_binding # "local variable"

So, in an IRB session:

irb(main):001:0> a = "I am a local variable"
=> "I am a local variable"
irb(main):002:0> eval("a", binding)
=> "I am a local variable"

When we pass a block to the method, the binding preserves it.

def bindng
return binding

s = bindng{|v| puts v}
eval("yield('subbu')", s)

I don't know how this can be used though.

Another example that talks about binding with a nice context to use it:

No comments: