Sunday, February 17, 2008

eval

eval("foo", binding)
Evaluate string in the context of binding. In this case 'foo' is executed as code in the context of binding. The second parameter is optional. It could either be a proc object or a binding object. If the second parameter is missing then the scope is set to current.

class_eval
Evaluate the code inside the context of a class. Example:

Array.class_eval <<-addons
def total
self.inject do |s,e|
s+e
end
end
addons

a=[1,2,3,4]
puts a.total


We can say something like "Array.class_eval('some goes here')" and the code will be executed within the context of Array class.

module_eval
Same as class_eval

Here is an excellent article:
http://www.infoq.com/articles/eval-options-in-ruby

No comments: