简体   繁体   English

class_eval问题Ruby

[英]class_eval issue Ruby

I am trying to use class_eval to create a method metaprogrammatically if the method that's called starts with "plus". 如果所调用的方法以“ plus”开头,则我尝试使用class_eval元编程创建方法。 However, I'm having trouble putting together the actual syntax of the class_eval 但是,我在整理class_eval的实际语法时遇到了麻烦

class Adder
  def initialize(my_num)
    @my_num = my_num
  end
  def my_num
    @my_num
  end
end
    def method_missing(meth, *args)
        my_meth = meth.to_s
        #puts my_meth[0, 4]
        if my_meth[0, 4] == "plus" then #/plus\d/ then
            num = my_meth.slice(/\d+/).to_i

            original_num = self.my_num.to_i
            my_sum = original_num + num
            class_eval{ eval{"def #{meth}; @my_int = #{my_sum} return @my_int end\n"}}
        end
        else
        super
    end


y = Adder.new(12)
puts y.plus10

When the plus10 (or whatever number) is called, the newly created method should add that number to the integer that's being called on, and produce the new sum. 当调用plus10(或任何数字)时,新创建的方法应将该数字加到正在调用的整数上,并产生新的总和。

Thanks 谢谢

Try this: 尝试这个:

class Adder
  def initialize(my_num)
    @my_num = my_num
  end
  def my_num
    @my_num
  end
  def method_missing(meth, *args)
    my_meth = meth.to_s
      if my_meth[0, 4] == "plus" then
        num = my_meth.slice(/\d+/).to_i
        original_num = my_num
        my_sum = original_num + num
        self.class.class_eval do
          define_method "#{meth}" do
            my_int = my_sum
          end
        end
        send meth
      else
        super
      end
  end
end
y = Adder.new(12)
puts y.plus10  # => 22

UPDATE 更新

and this is slightly improved version: 这是稍微改进的版本:

class Adder
  def initialize(num)
    @num = num
  end

  def method_missing(name, *args)
    name_string = name.to_s
    if /^plus(\d+)/ =~ name_string
      sum = Regexp.last_match(1).to_i + @num
      self.class.class_eval do
        define_method "#{name}" do
          sum
        end
      end
      send name
    else
     super
    end
  end
end

y = Adder.new(12)
puts y.plus10  # => 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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