10

Wenn ich Code ausführen darunter Fehler aus:Warum kann ich Super nicht in define_method mit Überlademethode aufrufen?

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

Ich bin nicht sicher, was das Problem ist.

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) 

Antwort

13

Die Fehlermeldung ist ziemlich beschreibend. Sie müssen explizit Argumente super geben, wenn Sie es innerhalb von define_method Block nennen:

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

Dank für Ihre Hilfe. Es funktioniert wie ein Zauber. –