Monkey Patching (Ruby)

Monkey patching is reopening an existing class — even a built-in one like String or Integer — to add or change methods at runtime. It's powerful Ruby flexibility that must be used with care.

Ruby

Ruby classes are 'open': you can reopen String, Array, or any class anywhere and add methods or redefine existing ones. Those changes apply globally to all instances, including objects created elsewhere. This lets you extend core types to fit your domain.

The danger is that changes are global and invisible: redefining a core method can break other code or libraries that relied on the original, and conflicts between two patches are hard to trace. That's why monkey patching is sometimes called a code smell when overused.

Safer alternatives exist: refinements scope a patch to where it's activated, and adding behavior via a mixin module keeps it explicit. Reserve global monkey patching for small, well-named additions you fully control.

Examples

Ruby

class String
  def shout
    upcase + "!"
  end
end

puts "hello".shout

Output:

HELLO!

Learn it in a lesson

See also

Back to the Dictionary