rubyguides

Ruby class_eval and instance_eval

Ruby gives you ways to reopen classes and objects at runtime and define new behaviour on the fly. Two methods that do exactly this are class_eval and instance_eval. They sound similar and both accept a block, but they work in fundamentally different ways. Getting the distinction right is essential for writing clean metaprogramming code.

Intro context

The reason these methods matter is that Ruby treats classes and objects as first-class runtime values. That means you can decide later whether a method belongs on a class, on every instance of that class, or on just one specific object. In practice, this is what makes frameworks, DSLs, and helper libraries feel expressive instead of rigid.

When you use them carefully, class_eval and instance_eval let you choose the right level of scope for a change. A class-level change is useful when every instance should share the behavior. An object-level change is better when you are customizing one instance or building a block-based API that should read naturally.

What class_eval Does

class_eval evaluates a block in the context of a class or module. It temporarily reopens that class, as if you were inside its original definition. Inside the block, self is the class itself, and any method you define with def becomes an instance method available to every object created from that class.

class Greeter
end

Greeter.class_eval do
  def hello
    "Hello from class_eval"
  end
end

Greeter.new.hello # => "Hello from class_eval"

class_eval is available on every Module and Class object. You can use it on built-in classes too.

This first example shows class_eval adding an instance method to Greeter, but the same technique works on any Module or Class object, including built-in classes like String. When you call class_eval on String, the block runs as if you had reopened the class definition, so def creates an instance method available on every string in the program.

String.class_eval do
  def question?
    end_with?("?")
  end
end

"Is this a question?".question? # => true
"No it is not".question?         # => false

What instance_eval Does

instance_eval evaluates a block in the context of a specific object. Inside the block, self is that particular object, not the class it belongs to. This changes how method definitions behave: def inside instance_eval creates a singleton method — a method that belongs only to the receiver object.

class Person
  def initialize(name)
    @name = name
  end
end

alice = Person.new("Alice")
bob   = Person.new("Bob")

alice.instance_eval do
  def tagline
    "I am #{@name}"
  end
end

alice.tagline   # => "I am Alice"
bob.tagline     # => NoMethodError (singleton method, only alice has it)

The same applies when you call instance_eval on a class. A class is itself an object (an instance of Class), so self inside the block is the class itself, and def creates a class method.

The Person example above shows instance_eval on a regular object, but calling it on a class produces a different result. A class is itself an object, so self inside the block is the class itself, and def creates a class method. This is why you sometimes see instance_eval used to define methods on a module or class directly rather than inside a class << self block.

class Calculator
end

Calculator.instance_eval do
  def brand
    "SuperCalc"
  end
end

Calculator.brand # => "SuperCalc"

The Key Difference

The core of it:

  • class_evalself is the class. def creates instance methods (shared by all objects of that class).
  • instance_evalself is the receiver object. def creates singleton methods (only that object has them).

Here is a side-by-side demonstration using the same Dog class:

class Dog
end

# class_eval defines an instance method
Dog.class_eval do
  def bark
    "Woof!"
  end
end

dog = Dog.new
dog.bark      # => "Woof!"
Dog.bark      # => NoMethodError (bark belongs to instances, not the class)

# instance_eval defines a singleton method on the specific object
dog2 = Dog.new
dog2.instance_eval do
  def growl
    "Grrr!"
  end
end

dog2.growl    # => "Grrr!"
dog.bark      # still works — dog still has the instance method
dog.growl     # => NoMethodError (only dog2 has growl)

This distinction matters. If you call instance_eval on a class, you get class methods because the class itself is the object. If you call class_eval on a class, you get instance methods.

In practice, that means class_eval is the better fit when you want to add shared behavior to a type. instance_eval is better when you need to customize one specific object, or when the object itself is serving as the receiver for a DSL block.

Accessing Private Methods

One practical use for instance_eval is reaching inside an object to call private methods or read instance variables that would normally be hidden.

class Vault
  private
  def secret_code
    "xyz-123"
  end
end

vault = Vault.new
vault.instance_eval { secret_code } # => "xyz-123"

class_eval does not give you this same direct access to an instance’s internals. It changes self to the class, not to a specific object.

Building DSLs

Both methods see heavy use in DSL (Domain-Specific Language) construction. instance_eval is particularly common because DSL blocks often want a single implicit receiver.

class HtmlBuilder
  def initialize(&block)
    instance_eval(&block)
  end

  def div(wrapped_content = nil, &block)
    if block
      "<div>#{div(wrapped_content, &block)}</div>"
    else
      "<div>#{wrapped_content}</div>"
    end
  end
end

html = HtmlBuilder.new
result = html.div { div("Nested content") }
# => "<div><div>Nested content</div></div>"

In this pattern, instance_eval(&block) turns the block’s self into the HtmlBuilder instance, so you can call div directly without an explicit receiver. class_eval is less useful here because you rarely want to operate on a class in a DSL context.

When you build DSLs, the tradeoff is readability versus surprise. instance_eval gives you a concise API, but it also hides the receiver. That is great for small configuration blocks, yet it can be confusing if the block starts doing too much work. Keep the block focused and the method names obvious.

If the block needs to stay readable for someone who is not writing the DSL, keep the method names short and the nesting shallow. That makes the runtime trick feel like a convenience instead of a hidden language.

Block Form vs String Form

Both methods accept a string instead of a block. You will almost always prefer the block form.

# Block form — preferred
String.class_eval do
  def shout
    upcase + "!"
  end
end

# String form — rarely needed
String.class_eval "def shout; upcase + '!'; end"

Blocks are better because they integrate with your editor’s syntax highlighting, they capture local variable bindings (enabling closures), and they avoid the security risks that come with evaluating arbitrary string input.

That rule is worth remembering even if you rarely write metaprogramming code. String-based evaluation makes debugging harder and opens the door to accidental code injection. Blocks keep the code in normal Ruby syntax, which is easier to search, refactor, and review.

Adding Multiple Methods Dynamically

A common metaprogramming pattern combines class_eval with iteration to define many methods at once. This is cleaner than writing each method by hand.

class Product
  attr_accessor :name, :price, :stock
end

fields = [:name, :price, :stock]

Product.class_eval do
  fields.each do |field|
    define_method("#{field}_formatted") do
      value = send(field)
      field == :price ? "$#{'%.2f' % value}" : value.to_s
    end
  end
end

Inside class_eval, define_method works naturally because the block executes as if it were inside the class body. Using instance_eval for this would not make sense — you would be defining methods on one specific object, not on the class.

If you are building frameworks or internal libraries, this pattern is common. It lets you define a family of methods from metadata, configuration files, or column names without writing each method manually. That can save time, but it works best when the generated API still feels predictable to the person reading the code.

The safest version of this pattern is the one you can explain in a single sentence. If the class body becomes impossible to scan, step back and ask whether a plain method or a module would be easier to understand.

If you want to see another piece of Ruby metaprogramming in action, continue with Ruby Introspection and Reflection. It shows how to inspect objects at runtime before you decide whether class_eval or instance_eval is the right tool. That pairing matters because inspection helps you choose the right scope before you change it. It also gives you the vocabulary to explain why a change belongs on a class, a single object, or a block-based DSL.

See Also