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