Why I can not call super in define_method with overloading method?

China☆狼群 提交于 2020-01-10 14:12:40

问题


When I run code below it raise error:

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

I am not sure what is the problem.

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)

回答1:


The error message is quite descriptive. You need to explicitly pass arguments to super when you call it inside of define_method block:

mem[args] = super(*args)


来源:https://stackoverflow.com/questions/20238661/why-i-can-not-call-super-in-define-method-with-overloading-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!