[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: Re: Why I can not call super in define_method with overloading method?
From: Mike Stok <mike () stok ! ca>
Date: 2013-11-27 12:32:13
Message-ID: 961B9CFF-D93B-49FE-A1D3-B28B270A8DD1 () stok ! ca
[Download RAW message or body]
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 Van <lists@ruby-forum.com> wrote:
> 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)
>
> --
> Posted via http://www.ruby-forum.com/.
--
Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic