1

It seems like class_eval (takes a string that it turns into code) and declaring the class with new def methods are essentially the same thing.

Are they really equivalent? What are the pros and cons of each?

DFBerry
  • 1,818
  • 1
  • 19
  • 37

1 Answers1

1

There's almost no difference between usual method defining and block evaluating:

bench(1000000) do
  class A; def test; end end
end
=> 2.5 sec

class B; end
bench(1000000) do
  B.class_eval{ def test; end }
end
=> 2.75 sec

But here's big difference with string evaluating:

bench(1000000) do
  B.class_eval("def test1; end")
end
=> 24.02 sec

Anyway, these constructions should be used by their purposes, if you do the metaprogramming then use class or instance evaluating, if you're just defining a method, do not be too clever in trifles.

megas
  • 21,401
  • 12
  • 79
  • 130