Lai Yu-Hsuan Lai Yu-Hsuan - 5 months ago 15
Ruby Question

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?

Answer

With class_eval you can do more dynamic things:

>> met = "hello" #=> "hello"
>> String.class_eval "def #{met} ; 'hello' ; end" #=> nil
>> "foo".hello #=> "hello"