Recipe 10.12. Evaluating Code in an Earlier ContextProblemYou've written a method that evaluates a string as Ruby code. But whenever anyone calls the method, the objects referenced by your string go out of scope. Your string can't be evaluated within a method. For instance, here's a method that takes a variable name and tries to print out the value of the variable.
The eval code only works when it's run in the same context as the variable definition. It doesn't work as a method, because your local variables go out of scope when you call a method.
SolutionThe eval method can execute a
DiscussionA Binding object is a bookmark of the Ruby interpreter's state. It tracks the values of any local variables you have defined, whether you are inside a class or method definition, and so on. Once you have a Binding object, you can pass it into eval to run code in the same context as when you created the Binding. All the local variables you had back then will be available. If you called Kernel#binding within a class definition, you'll also be able to define new methods of that class, and set class and instance variables. Since a Binding object contains references to all the objects that were in scope when it was created, those objects can't be garbage-collected until both they and the Binding object have gone out of scope. See Also
|
Saturday, October 31, 2009
Recipe 10.12. Evaluating Code in an Earlier Context
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment