On Sun, 1 Jan 2006, Daniel Berger wrote:

> ara.t.howard / noaa.gov wrote:
>> On Sun, 1 Jan 2006, Daniel Berger wrote:
>
> <snip>
>
>>    harp:~ > cat a.rb
>>    def memoize_to_file(name, file)
>>      cache = Hash.new.update(Marshal.load(File.read(file))) rescue {}
>>      (class << self; self; end).class_eval do
>>         define_method(name) do |*args|
>>            unless cache.has_key?(args)
>>              cache[args] = method(name).call(*args)
>>              File.open(file, "wb+"){|f| Marshal.dump(cache, f) }
>>            end
>>            cache[args]
>>         end
>>      end
>>    end
>>
>>    def fib(n)
>>     return n if n < 2
>>     fib(n-1) + fib(n-2)
>>    end
>>
>>    memoize_to_file "fib", "fib.cache"
>>    n = fib 10
>>    p n
>
> As is, I get a stack level too deep error on Windows.  If I change the
> "cache[args] =" to "cache[args] ||=", I always get back nil.
>
> I'm probably being thick here, but any help is appreciated.

sorry, don't know how that's running on linux in the first place... you need:

   --- a.rb	2005-12-31 20:30:59.000000000 -0700
   +++ b.rb	2005-12-31 20:31:10.000000000 -0700
   @@ -1,9 +1,10 @@
    def memoize_to_file(name, file)
   +  meth = method(name)
      cache = Hash.new.update(Marshal.load(File.read(file))) rescue {}
      (class << self; self; end).class_eval do
         define_method(name) do |*args|
            unless cache.has_key?(args)
   -          cache[args] = method(name).call(*args)
   +          cache[args] = meth.call(*args)
              File.open(file, "wb+"){|f| Marshal.dump(cache, f) }
            end
            cache[args]

with that it works for me on linux and windows.

cheers.

-a
-- 
===============================================================================
| ara [dot] t [dot] howard [at] noaa [dot] gov
| all happiness comes from the desire for others to be happy.  all misery
| comes from the desire for oneself to be happy.
| -- bodhicaryavatara
===============================================================================