Ruby performance: define a method with define_method or eval

When looking at ActiveSupport source code, I noticed that sometimes eval used in places where define_method enough.

Example: ActiveSupport: Module.delegate

I believe that define_method a cleaner and safer way of doing things. What are the advantages of eval over define_method ? Perfomance, memory usage, something else?

+7
source share
3 answers

When you use define_method, the method you define cannot accept a block .

Its pretty well known that due to a lack of argument blocks in Ruby 1.8, Class # define_method cannot define methods that accept blocks.

 def x *args, █ end # => works! define_method(:x) {|*args,&block| } # => SyntaxError: compile error 

To define a method, a block is required:

 "def #{prefix}#{method}(*args, &block)" # def customer_name(*args, &block) 

So define_method cannot be used.

+3
source

I found this to be a very good article on this subject: http://blog.grayproductions.net/articles/eval_isnt_quite_pure_evil .

+3
source

I don’t know what is the reason in this particular case, but define_method takes a block that is a closure (contains local variables of the place in which it was defined), which can lead to a significant increase in memory consumption to a simple eval .

+1
source

All Articles