AI Code

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

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
>>'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

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

Got any Ruby Language Question?