class_eval and instance_eval in Ruby
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.
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.
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.
class Calculator
end
Calculator.instance_eval do
def brand
"SuperCalc"
end
end
Calculator.brand # => "SuperCalc"
The Key Difference
The core of it:
class_eval—selfis the class.defcreates instance methods (shared by all objects of that class).instance_eval—selfis the receiver object.defcreates 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.
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.
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.
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.
See Also
- Ruby Metaprogramming Basics — broader overview of Ruby’s metaprogramming tools
- The eval Method in Ruby — how Ruby’s raw
evalworks and when to avoid it - define_method in Ruby — creating methods dynamically with
define_method