July 2011
Intermediate to advanced
400 pages
8h 46m
English
There are some variations on the eval theme in the form of the methods named instance_eval, module_eval, and class_eval. The instance_eval method can be called from a specific object, and it provides access to the instance variables of that object. It can be called either with a block or with a string:
instance_eval.rb
class MyClass
def initialize
@aVar = "Hello world"
end
end
ob = MyClass.new
p( ob.instance_eval { @aVar } ) #=> "Hello world"
p( ob.instance_eval( "@aVar" ) ) #=> "Hello world"The eval method, on the other hand, cannot be called from an object in this way because it is a private method of Object (whereas instance_eval is public):
p( ob.eval( "@aVar" ) ) # This won't work!
In fact, you could explicitly change the ...
Read now
Unlock full access