Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 134 ยท Metaprogramming

instance_eval and class_eval

Learn how Ruby's instance_eval, class_eval, instance_exec and class_exec change self inside a block, how they differ, and how they power DSLs and test helpers.

Inside any Ruby code, self is the object that receives method calls without an explicit receiver, and it decides which instance variables you see. Usually self is fixed by where the code is written: in an instance method it is the object, in a class body it is the class. Ruby lets you change self for a block of code. That is what instance_eval, class_eval and their _exec variants do, and it is the key trick behind DSLs such as route tables, configuration blocks and test frameworks.

This lesson explains each method, how they differ, why instance_exec exists, and how to use them without creating a mess. It assumes you know blocks, closures and instance variables. The next lesson, Building DSLs, builds on it.

What self is, and how a block can change it

Normally a block remembers the self from where it was written. Watch what happens when we override that.

Ruby Changing self for a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

counter.instance_eval { ... } runs the block with self set to counter. The block can read and write the object's instance variables directly, even though @count has no public reader. That is both the power and the danger: instance_eval ignores encapsulation. Use it deliberately.

The first line prints outside: main. main is the top-level object every script starts with.

instance_eval: self is the object

instance_eval also sets the default definee: a def inside the block defines a singleton method on the object.

Ruby def inside instance_eval makes a singleton method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

On a plain object it makes a method for that one object. On a class, instance_eval treats the class as an object, so def create becomes a class method. Remember this rule: instance_eval defines methods on the singleton class.

class_eval: self is the class

class_eval (also spelled module_eval) is for classes and modules. It sets self to the class and makes def define instance methods, as if you had reopened the class.

Ruby Reopening a class with class_eval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The two spellings give the same result, but class_eval takes a block, so it can be used from a method, in a loop, or on a class stored in a variable, none of which the class keyword can do. It also sees the local variables around it, which class Dog ... end does not (the class keyword starts a fresh scope).

Method self inside the block def definesโ€ฆ
obj.instance_eval { } obj singleton methods of obj
Klass.class_eval { } Klass instance methods of Klass
Klass.instance_eval { } Klass singleton (class) methods of Klass

Passing arguments: instance_exec and class_exec

instance_eval yields the object itself to the block as its only argument, and it cannot pass anything else. The _exec variants fix that: any arguments you give are passed on to the block.

Ruby instance_exec passes arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

instance_exec(args) { |a| ... } is the form you want when the block takes parameters, and the way to give a lambda arguments of your own. A lambda passed to instance_eval always receives the object as its single argument, so a lambda that takes none fails with wrong number of arguments (given 1, expected 0). For DSLs, instance_exec is usually the right default.

The closure still works

Switching self does not hide local variables. Blocks are closures: they keep seeing the locals where they were written, while self and instance variables come from the new receiver.

Ruby Locals from outside, instance variables from inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is why label and @label give different answers. Mixing the two kinds of names is exactly what makes instance_eval DSLs powerful (the user's local variables stay available) and confusing (is name a local or a method call on the new self?).

A tiny DSL: configuration blocks

Here is the standard shape of a configuration DSL. The method yields nothing; it just evaluates the user's block against a builder object.

Ruby A configuration DSL with instance_eval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside the block, host "example.test" is a method call on the ServerConfig instance, because self is the builder. The user writes no config. prefix and no block parameter, which is what makes it read like a small language. The price: the block's code cannot freely call methods of the surrounding object, because self changed. That leads to the most common DSL bug.

The self problem: calling the outer object

Ruby The outer method disappears (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The run ends with main.rb:16:in 'block in App#setup': undefined local variable or method 'default_host' for an instance of ServerConfig (NameError). Inside the block self is the ServerConfig, so default_host is looked up there, not on App. There are three common fixes:

  1. Copy it into a local first: h = default_host before the call. Locals survive because of the closure.
  2. Yield the builder instead of switching self: yield config, and the user writes c.host default_host. This keeps the outer self intact and is the explicit, safest style.
  3. Keep a reference to the outer object: app = self before the block, then app.default_host.

Many libraries support both styles: if the block takes a parameter (arity == 1), they yield the builder; otherwise they use instance_eval. You can check block.arity to decide.

Ruby Supporting both block styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Evaluating strings, and why to avoid it

Both methods also accept a string of code instead of a block. The code is parsed at runtime.

Ruby String evaluation, and what it costs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This generates six methods from text. The extra arguments __FILE__ and __LINE__ + 1 tell Ruby where the code "lives", so error messages and stack traces point to the right line. String evaluation is how attr_accessor is conceptually built, and it was once the fastest way to define methods, but it has two serious drawbacks: it is a security risk if any part of the string comes from outside, and it hides code from tools and linters. With define_method (see the previous lesson) a block does the same job safely, so prefer blocks. eval and Binding discusses the risks in detail.

When to use which

  • instance_eval / instance_exec: DSL blocks, test helpers that peek into an object, building singleton methods.
  • class_eval / class_exec: adding methods to a class that you hold in a variable, shared setup code applied to several classes, or code inside hooks like included.
  • Prefer _exec whenever the block needs arguments, or when you will pass a lambda.
  • Avoid in application logic where a normal method call works; instance_eval breaks encapsulation, confuses readers about what self is, and defeats autocompletion.

A last hint: a gem that offers a configuration block (Gem.configure do |config| ... end) is yielding; one that offers a keyword-style block (route do get "/" end) is evaluating. Both are fine; choose one and document it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does obj.instance_eval { @name } do?

    instance_eval changes self to the receiver, so the block can access its instance variables, bypassing normal encapsulation.
  2. 2. Inside Dog.class_eval { def bark; end }, what does def define?

    class_eval behaves like reopening the class, so def defines instance methods.
  3. 3. Why use instance_exec instead of instance_eval?

    instance_exec forwards its arguments to the block, which instance_eval cannot do. With instance_eval the only argument is the object itself.
  4. 4. In a DSL block run with instance_eval, a call to a method of the surrounding object fails. Why?

    The block's self is the builder, so method calls without a receiver go to it. Copy the value to a local, yield the builder, or use an explicit reference to the outer object.
  5. 5. Why are block forms of eval preferred over string forms?

    String evaluation compiles text at runtime: it is a security risk with untrusted input and invisible to linters and debuggers. Blocks are parsed with the rest of the file.

Summary

  • instance_eval { } runs a block with self set to the receiver; def inside defines singleton methods.
  • class_eval { } runs it with self set to a class or module; def defines instance methods, and unlike class, the block sees outer locals.
  • instance_exec and class_exec pass arguments to the block; use them for lambdas and parameterised DSL blocks.
  • Local variables still come from the closure, but method calls and instance variables follow the new self.
  • DSLs either evaluate the block (clean syntax, outer self hidden) or yield a builder (explicit, safe). Supporting both with block.arity is common.
  • Prefer blocks over strings, and avoid these tools where plain method calls will do.

Next: Building DSLs