Sunday, March 8, 2009

Hard Stuff in Ruby- Part 4: Bindings and eval

Bindings and eval are advanced topics. For starters, get into irb (or rails console), and try a basic eval statement:

eval "t = 'lksjafsdn'"

same exact result as just typing:

t = 'lksjafsdn'

But there is one main difference in function. You can also pass in a binding object as a second parameter. What is a "binding?" It's the context where the code is evaluated, so you can still access variables in those contexts. So you can pass around a context, return it from a function, etc.

Okay, so what else can you do with a binding? You can change it. Let's say that you are trying to see inside of an object that you created. Just use cb(Object,class,etc.) So now your inside the object, and instead of saying "self.method_name", you can just say "method_name". So naturally, just typing "self" returns the object that you are demon possessing. Freaky.

You can keep changing the bindings, but if you leave your main context without saving it somehow, there's no way back.
or is there...
Whoops. Just kidding. Here we go: cb(TOPLEVEL_BINDING)

Either way, this is still worth checking out. It gives a few other interesting options for dealing with this kind of stuff:
http://github.com/mattknox/repl/tree/master


If you want a good reference for basics on bindings, here's a good one

http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc/style/print


Okay, so you have a lot of specific ways to evaluate in particular contexts. Sweet. Anything else?

Glad you asked. Here you go. We covered basics of eval, but there's also class_eval, module_eval, and instance_eval.

They all act pretty much as expected. Conceptually, you can now stowaway in an object without changing your binding. The following are equivalent:

MyClass.class_eval "some code"
and
cb(MyClass)
eval "some code"



Hard stuff list:
-Metaprogramming
-Blocks
-Lambdas
-eval methods
-bindings
-Singleton
-Method Missing

No comments:

Post a Comment