如果调用的方法以“plus”开头,我试图使用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
当调用plus10(或任何数字)时,新创建的方法应该将该数字添加到被调用的整数中,并产生新的总和。
由于
答案 0 :(得分:1)
试试这个:
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
<强>更新强>
这是稍微改进的版本:
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