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:

 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 } ​# => ...

Get Metaprogramming Ruby 2 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.