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… Please help me!!!

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)

The error message should point you at the line in question:

mem[args] = super

you can make it work by explicitly passing in the arguments like:

mem[args] = super *args

And the output should be the expected showing that the calculation’s
result for a particular set of arguments has been memoized:

ratdog:tmp mike$ ruby try.rb
Calculation for [5, 10, 10, 10, 10, 10, 10, 10]
93.75
93.75
Calculation for [10, 10, 10, 10, 10, 10, 10, 10]
100.0
100.0

I’m not sure if I can correctly and clearly explain why you can’t do it,
so I’ll leave that so someone else.

Hope this helps,

Mike

On Nov 27, 2013, at 4:26 AM, Bunlong V. [email protected] wrote:

private
define_method(method) do |*args|
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)


Posted via http://www.ruby-forum.com/.

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

super() “With parenthesis”

Calculation for []
test.rb:9:in percentage_calculation': undefined method*’ for
nil:NilClass (NoMethodError)
from test.rb:3:in total' from test.rb:21:inblock (2 levels) in mem_result’
from test.rb:30:in `’

It seems passed the first error, was not it?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs