Ruby Language

Monkey Patching in Ruby

Monkey patching a class

Monkey patching is the modification of classes or objects outside of the class itself.

Sometimes it is useful to add custom functionality.

Example: Override String Class to provide parsing to boolean

class String 
  def to_b
    self =~ (/^(true|TRUE|True|1)$/i) ? true : false
  end
end

As you can see, we add the to_b() method to the String class, so we can parse any string to a boolean value.

>>'true'.to_b 
=> true
>>'foo bar'.to_b
=> false

Monkey patching an object

Like patching of classes, you can also patch single objects. The difference is that only that one instance can use the new method.

Example: Override a string object to provide parsing to boolean

s = 'true'
t = 'false'    

def s.to_b
  self =~ /true/ ? true : false
end

>> s.to_b
=> true
>> t.to_b
=> undefined method `to_b' for "false":String (NoMethodError)

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow