0
0
RubyConceptBeginner · 3 min read

What is Monkey Patching in Ruby: Explanation and Examples

In Ruby, monkey patching means changing or adding methods to existing classes or modules at runtime. It lets you modify built-in or third-party code without changing the original source.
⚙️

How It Works

Monkey patching in Ruby works by reopening an existing class or module and redefining or adding methods. Imagine you have a recipe book, and you decide to add your own notes or change a recipe without rewriting the whole book. Ruby lets you open that book anytime and make your changes.

This means you can fix bugs, add features, or change behavior of code that you did not originally write. However, since these changes affect all uses of that class or module, it’s like changing a shared recipe that everyone uses — so you must be careful to avoid unexpected results.

💻

Example

This example shows how to add a new method to Ruby's built-in String class using monkey patching.

ruby
class String
  def shout
    self.upcase + "!"
  end
end

puts "hello".shout
Output
HELLO!
🎯

When to Use

Use monkey patching when you need to fix or extend behavior of existing classes without changing their original code. For example, you might add helper methods to built-in classes or patch bugs in third-party libraries.

It is common in Ruby gems and frameworks to customize behavior. But use it carefully because it changes global behavior and can cause conflicts if multiple patches affect the same methods.

Key Points

  • Monkey patching lets you change or add methods to existing classes at runtime.
  • It is powerful but can cause unexpected side effects if not used carefully.
  • Commonly used to fix bugs or add features to built-in or third-party code.
  • Always document monkey patches clearly to avoid confusion.

Key Takeaways

Monkey patching allows modifying existing classes or modules dynamically in Ruby.
It is useful for fixing bugs or adding features without changing original source code.
Use monkey patching carefully to avoid conflicts and unexpected behavior.
Always clearly document any monkey patches you add to your codebase.