Lai Yu-Hsuan Lai Yu-Hsuan - 1 year ago 82
Ruby Question

monkey patching vs class_eval?

class String
def hello

String.class_eval {
def world

=> "hello"
=> "world"

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

Answer Source

With class_eval you can do more dynamic things:

>> met = "hello" #=> "hello"
>> String.class_eval "def #{met} ; 'hello' ; end" #=> nil
>> "foo".hello #=> "hello"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download