On 02/04/2010 12:46 PM, Fredrik Johansson wrote:
> I created a small "lab tool" that makes life easier for me. It's
> basically a Hash that you can't put values into, the values can only
> be obtained from a method that you define. I created it with the idea
> that a calculation should only have to be done once. I paste the
> README file below.
> Please let me know what you think!

http://raa.ruby-lang.org/project/memoize/

>   A Hash subclass that defines its values from a specified method.
>   Use it by creating a subclass of MethodHash, and define a method
>   with the name "mymethod" in it.
>   Like this (same code in samples/samples.rb):
> 
>   # 1. Simple use
>   class AddOne < MethodHash
>     def mymethod(a)
>       sleep 3
>       a + 1
>     end
>   end
> 
>   a = AddOne.new
>   a            #  {}
>   a[1]         #  2
>   a[7]         #  8
>   a            #  {1=>2, 7=>8}
>   puts a.dump  #  --- !map:AddOne
>                #  1: 2
>                #  7: 8

You can do this with a Hash already:

irb(main):001:0> a = Hash.new {|h,k| printf("calc %p\n",k);h[k] = k + 2} 
# add two
=> {}
irb(main):002:0> a[1]
calc 1
=> 3
irb(main):003:0> a[1]
=> 3
irb(main):004:0> a[5]
calc 5
=> 7
irb(main):005:0> a[5]
=> 7
irb(main):006:0> a
=> {1=>3, 5=>7}
irb(main):007:0>

Granted, serialization to a file needs a few lines more.

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/