O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

instance_eval()

Where you learn another way to mix code and bindings at will.

The following program demonstrates BasicObject#instance_eval, which evaluates a block in the context of an object:

blocks/instance_eval.rb
 
class​ MyClass
 
def​ initialize
 
@v = 1
 
end
 
end
 
 
obj = MyClass.new
 
 
obj.instance_eval ​do
 
self ​# => #<MyClass:0x3340dc @v=1>
 
@v ​# => 1
 
end

The block is evaluated with the receiver as self, so it can access the receiver’s private methods and instance variables, such as @v. Even if instance_eval changes self, the block that you pass to instance_eval can still see the bindings from the place where it’s defined, like any other block:

 
v = 2
 
obj.instance_eval { @v = v }
 
obj.instance_eval { @v } ​# => ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required