Special Types of eval

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 ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.