我经常使用begin … end block语法记住
Ruby方法:
$memo = {} def calculate(something) $memo[something] ||= begin perform_calculation(something) end end
但是,这里有一个问题.如果我通过一个保护子句从begin … end block提前返回,则结果不会被记忆:
$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
这有效,但我不喜欢它,因为:
>很容易忘记在这种情况下我不允许使用返回.
>在许多条件下,它会使代码混乱而不是保护条款.
除了避免回归之外,还有更好的成语吗?