Search code examples
rubymetaprogrammingmonkeypatching

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?


Solution

  • With class_eval you can do more dynamic things:

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