Hacker News new | ask | show | jobs
by vidarh 537 days ago
If you're first going to golf it, endless-def:

    def fib(n, cache=Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }) = cache[n]
2 comments

It's actually kind of ungolfed. The default version would be just

    fib = Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }
    
    fib[7145]
This is the proper Ruby form since it relies on the [] operator and is therefore substitutable for any other callable esp. procs/lambdas, and able to wrap them as well.

This isn’t just golf, it’s an excellent way to pass around a lazily computed, self-caching closure. I use it often in preference to memoization gems.

Aside from noting the false/nil equivalence concern, the original article seems over-engineered to me. Excessive metaprogramming is a common trap for Ruby devs.

IMHO, the mamul form is even better for golf, F(n) in O(n log n)