From: Ben Giddings Date: 2003-09-15T07:29:40+09:00 Subject: Re: performance and style advice requested Some style advice: On Sunday, September 14, 2003, at 12:44 PM, Alex Martelli wrote: > # > # factorial, memoized via an Array > # > $_fact_memo=[1,1,2,6,24,120,720] Ugh. This is what really bothers me about python programs. Ugly underscores. > def fact(x) > # factorial of x (0 if x<0) > result = $_fact_memo[x] > if !result > return 0 if x<0 > result = $_fact_memo[x] = x*fact(x-1) > end > return result > end Hmm, how about def fact(x) $fact_memo[x] ||= if x<0 0 else x*fact(x-1) end end Although I'm pretty sure that a simple conditional is faster than an array lookup so this might be faster (and is easier to read): def fact(x) return 0 if x<0 $fact_memo[x] ||= x*fact(x-1) end You can take advantage of the fact Ruby expressions return their last value, and the return value of a function is the last expression's value. The rest is more complex so I'll quit while I'm ahead. :) Ben