Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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]


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)




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: