简体   繁体   中英

Ruby class_eval method

I'm trying to figure out how to dynamically create methods

class MyClass
  def initialize(dynamic_methods)
    @arr = Array.new(dynamic_methods)
    @arr.each { |m|
      self.class.class_eval do
        def m(*value) 
          puts value
        end
      end
    }
    end
end

tmp = MyClass.new ['method1', 'method2', 'method3']

Unfortunately this only creates the method m but I need to create methods based on the value of m, ideas?

There are two accepted ways:

  1. Use define_method :

     @arr.each do |method| self.class.class_eval do define_method method do |*arguments| puts arguments end end end 
  2. Use class_eval with a string argument:

     @arr.each do |method| self.class.class_eval <<-EVAL def #{method}(*arguments) puts arguments end EVAL end 

The first option converts a closure to a method, the second option evaluates a string (heredoc) and uses regular method binding. The second option has a very slight performance advantage when invoking the methods. The first option is (arguably) a little more readable.

define_method(m) do |*values|
  puts value
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM