How to Use class_eval in Ruby: Syntax and Examples
In Ruby,
class_eval is used to open a class and evaluate code inside its context, allowing you to add or change methods dynamically. You call it on a class and pass a block with the code you want to execute inside that class.Syntax
The class_eval method is called on a class object and takes a block of code. Inside this block, you can define methods or access class variables as if you were inside the class definition.
ClassName.class_eval { ... }: OpensClassNamefor modification.- The block contains method definitions or other class-level code.
ruby
ClassName.class_eval do # code to add or modify methods end
Example
This example shows how to add a new method to an existing class using class_eval. We add a method greet to the Person class that returns a greeting string.
ruby
class Person def initialize(name) @name = name end end Person.class_eval do def greet "Hello, my name is #{@name}!" end end person = Person.new("Alice") puts person.greet
Output
Hello, my name is Alice!
Common Pitfalls
Common mistakes when using class_eval include:
- Using
class_evalon an instance instead of a class, which will cause errors. - Not understanding that code inside the block runs in the class context, so instance variables refer to instances of the class, not the surrounding scope.
- Overusing
class_evalcan make code harder to read and debug.
Always ensure you use class_eval on a class object and keep the added code clear and simple.
ruby
class Dog end # Wrong: calling class_eval on an instance # dog = Dog.new # dog.class_eval { def bark; 'Woof!'; end } # This will raise an error # Right: calling class_eval on the class Dog.class_eval do def bark 'Woof!' end end dog = Dog.new puts dog.bark
Output
Woof!
Quick Reference
class_eval Cheat Sheet:
ClassName.class_eval { ... }: Open class to add or change methods.- Inside block,
def method_namedefines instance methods. - Use for metaprogramming and dynamic method creation.
- Be cautious to avoid confusing code and maintain readability.
Key Takeaways
Use
class_eval on a class to add or modify instance methods dynamically.Code inside the
class_eval block runs in the class context.Avoid calling
class_eval on instances; it must be called on classes.Keep
class_eval usage clear to maintain readable and maintainable code.