10

当我运行的代码在它下面募集错误:为什么我不能使用重载方法在define_method中调用super?

implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly. (RuntimeError).

我不知道是什么问题。

class Result 
    def total(*scores) 
    percentage_calculation(*scores) 
    end 

    private 
    def percentage_calculation(*scores) 
    puts "Calculation for #{scores.inspect}" 
    scores.inject {|sum, n| sum + n } * (100.0/80.0) 
    end 
end 

def mem_result(obj, method) 
    anon = class << obj; self; end 
    anon.class_eval do 
    mem ||= {} 
    define_method(method) do |*args| 
     if mem.has_key?(args) 
     mem[args] 
     else 
     mem[args] = super 
     end 
    end 
    end 
end 

r = Result.new 
mem_result(r, :total) 

puts r.total(5,10,10,10,10,10,10,10) 
puts r.total(5,10,10,10,10,10,10,10) 
puts r.total(10,10,10,10,10,10,10,10) 
puts r.total(10,10,10,10,10,10,10,10) 

回答

13

错误消息是相当具有描述性的。你需要明确地传递参数给super当你调用它define_method块内:

mem[args] = super(*args) 
+0

感谢你的帮助。它的工作就像一个魅力。 –

相关问题