Monkey patching have it’s legitimate uses, such as monkey patching float and fixnum to return money (currency jobs).
Or… you could monkey patch fixnum to play “FizzBuzz” for you:
Fixnum1 2 3 4 5
| class Fixnum def divisible_by_three? self % 3 == 0 end end
|
Testing1 2
| 3.divisible_by_three? 4.divisible_by_three?
|
More Fixnum1 2 3 4 5 6
| class Fixnum def fizzbuzz return “Fizz” if divisible_by_three? self end end
|
Rewriting Ruby inject method by monkey patching Array class
This is my attempt at reimplementing Ruby’s Array.inject method:
Reinventing the wheel1 2 3 4 5 6 7 8 9 10 11 12
| class Array def injectiano(accumulator = nil,&block) collection = self.dup accumulator ||= collection.shift collection.each do |item| accumulator = block.call(accumulator,item) end accumulator end end
|
There you have it. With great power comes great responsibility.