为什么我不能使用重载方法在define_method中调用super? [英] Why I can not call super in define_method with overloading method?

查看:37
本文介绍了为什么我不能使用重载方法在define_method中调用super?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在下面运行代码时会引发错误:

When I run code below it raise error:

不支持从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)

推荐答案

错误消息非常具有描述性.当您在 define_method 块中调用它时,您需要显式地将参数传递给 super:

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)

这篇关于为什么我不能使用重载方法在define_method中调用super?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆