midRuby

Explain open classes and the risks of Monkey Patching.

Updated May 17, 2026

Short answer

Open classes allow developers to reopen and modify any class definition (including core classes like String) at runtime. The risk is global namespace contamination and method collisions.

Deep explanation

In Ruby, classes are never closed. You can redefine or add methods to standard system classes like Array, Hash, or Integer anywhere in your application. While powerful for DSL construction, this technique (called Monkey Patching) is highly risky. If two separate external gems rewrite the same core method (e.g., String#blank?), the last gem loaded silently overwrites the previous one, leading to untraceable bugs.

Real-world example

ActiveSupport reopens core Ruby primitives to enrich them with helpful time extensions like ActiveSupport::Duration (3.days.ago).

Common mistakes

  • Monkey patching a method without keeping a copy of the original functionality or invoking `super`, breaking third-party gems that depend on standard class behavior.

Follow-up questions

  • What feature did Ruby introduce to safely isolate monkey patches?
  • How do you activate a refinement patch?

More Ruby interview questions

View all →