On 04.02.2010 14:02, Fredrik Johansson wrote:
>> You can do this with a Hash already:
> 
> Sure (I learned that from Ruby Best Practices. great book!), but I
> would like to argue that it's a bit more tidy to define a class (a
> subclass of MethodHash) in one place, which I can then reuse for
> anything I need to.

Well, there are multiple ways to reuse code and maintain DRY.  You do 
not necessarily need a class for that.

def add_two
   Hash.new {|h,k| h[k] = k + 2}
end

or, a more generic variant

def make_cache
   Hash.new {|h,k| h[k] = yield(k)}
end

AddTwo = make_cache {|x| x + 2}

etc.

> But I don't claim to have revolutionized the world
> with this. :)

Well, if you put a library in public then you probably want it to be 
used.  For that it needs to provide value to others.  If it doesn't it's 
probably not used and your effort may be in vain. :-)

> The use I have of it is that some calculations I have made that took
> some time to do, is easily available at any time later by just
> remembering the class name I used for it. Maybe the name MethodHash is
> misleading...

But what you actually want is the *instance* that does the caching, 
otherwise you'll loose cached values.  Or do you store results somewhere 
in a class instance variable?

Kind regards

	robert

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