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
end
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"
irb(main):003:0>
When we pass a block to the method, the binding preserves it.
def bindng
return binding
end
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:
http://railscasts.com/episodes/86
No comments:
Post a Comment