Ruby Language Monkey Patching in Ruby Monkey patching a class

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?