Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 266
Bunlong Avatar asked Nov 27 '13 09:11

Bunlong


1 Answers

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)
like image 145
Marek Lipka Avatar answered Sep 22 '22 14:09

Marek Lipka