什么是短路Ruby`start … end`块的正确习惯用法?

我经常使用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

话虽如此,我以前从未见过这样做过,所以它肯定不是惯用语.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...