seniorRuby

Explain Metaprogramming with class_eval, instance_eval, and module_eval.

Updated May 17, 2026

Short answer

instance_eval evaluates code in the context of the specific object instance (changing self). class_eval (and module_eval) evaluates code in the context of the class definition, creating instance methods for that class.

Deep explanation

These methods allow you to execute code blocks within a modified scope. instance_eval evaluates instructions with self bound to that precise object instance. If you define a method inside instance_eval, it becomes a singleton method exclusive to that single object. Conversely, class_eval (aliased as module_eval) is only available on Class and Module objects. It opens up the class context exactly as if you wrote class MyClass, meaning any method declared inside it becomes a standard instance method available to all current and future instances of that class.

Unlock with a Pro subscription to view this section.

View pricing

Real-world example

No real-world example available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Common mistakes

No common mistakes listed yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

Follow-up questions

No follow-up questions available yet.

Unlock with a Pro subscription to view this section.

Upgrade to Pro

More Ruby interview questions

View all →