什么是短路Ruby`start … end`块的正确习惯用法?
发布时间:2020-12-17 03:50:32 所属栏目:百科 来源:网络整理
导读:我经常使用begin … end block语法记住 Ruby方法: $memo = {}def calculate(something) $memo[something] ||= begin perform_calculation(something) endend 但是,这里有一个问题.如果我通过一个保护子句从begin … end block提前返回,则结果不会被记忆: $
我经常使用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 这有效,但我不喜欢它,因为: >很容易忘记在这种情况下我不允许使用返回. 除了避免回归之外,还有更好的成语吗? 解决方法
据我所知,开始……结束不能短路.你可以完全按照你要尝试做的事情:
$memo = {} def calculate(something) $memo[something] ||= -> do return 'foo' if something == 'bar' perform_calculation(something) end.call end 话虽如此,我以前从未见过这样做过,所以它肯定不是惯用语. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |