我經常memoize的使用begin ... end
塊語法Ruby方法:將Ruby`begin ... end`塊短路的恰當習慣用法是什麼?
$memo = {}
def calculate(something)
$memo[something] ||= begin
perform_calculation(something)
end
end
但是,這裏有一個疑難雜症。如果我通過保護條款從begin ... end
塊提前返回,結果不是memoized:
$memo = {}
def calculate(something)
$memo[something] ||= begin
return 'foo' if something == 'bar'
perform_calculation(something)
end
end
# does not memoize 'bar'; method will be run each time
我可以通過避免return
聲明避免這種情況:
$memo = {}
def calculate(something)
$memo[something] ||= begin
if something == 'bar'
'foo'
else
perform_calculation(something)
end
end
end
這工作,但我不」不喜歡它,因爲:
- 很容易忘記在這種情況下我不允許使用
return
。 - 在許多情況下,它將代碼與守衛子句相對立起來。
除了避開return
之外,還有更好的成語嗎?
上的一些公約一篇好文章:http://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem// – Anthony
我想**強烈建議不要使用全局緩存。儘可能保持變量的上下文非常重要,即儘可能使用''''樣式的實例變量。 – tadman
如果您的程序具有純函數,則可以進一步使用它並使用緩存方法調用它們自己。例如[cache-method](https://github.com/seamusabshere/cache_method)。如果需要,爲緩存提供離散API的好處是更容易切換持久化類型。 –