Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

monkey patching vs class_eval?

class String
  def hello
    "world"
  end
end

String.class_eval {
  def world
    "hello"
  end
}

"a".world
=> "hello"
"b".hello
=> "world"

They seems to do the same thing -- adding a method to a existing class. So what's the difference?

like image 384
Lai Yu-Hsuan Avatar asked Feb 22 '12 16:02

Lai Yu-Hsuan


People also ask

Is monkey patching a good practice?

But you should never consider this a standard technique and build monkey patch upon monkey patch. This is considered bad because it means that an object's definition does not completely or accurately describe how it actually behaves.

What does monkey patching do?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What is monkey patching give example?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

What is monkey patching in Ruby?

In Ruby, a Monkey Patch (MP) is referred to as a dynamic modification to a class and by a dynamic modification to a class means to add new or overwrite existing methods at runtime. This ability is provided by ruby to give more flexibility to the coders.


1 Answers

With class_eval you can do more dynamic things:

>> met = "hello" #=> "hello"
>> String.class_eval "def #{met} ; 'hello' ; end" #=> nil
>> "foo".hello #=> "hello"
like image 102
Michael Kohl Avatar answered Oct 25 '22 11:10

Michael Kohl