Ruby Language Monkey patching a class


Example

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