ruby - 尽早突破开始/结束 block

标签 ruby memoization

我想要一种方法来退出开始/结束 block ,同时仍然分配其结果分配给的变量。

def foo
  @foo ||= begin
    puts "running"

    return "leaving early" if true # would be some sort of calculation

    # Other calculations
  end
end

我希望发生的事情

> foo
running
=> leaving early
> foo
=> leaving early

实际发生了什么

> foo
running
=> leaving early
> foo
running
=> leaving early

代码不起作用,因为 return 没有设置 @foo 就退出了整个方法。使用 breaknext 只能在循环中使用。 begin block 中是否有任何工作符合我的想法?

我目前可以做到但希望避免的方法:

  • 在开始 block 中分配变量并返回
  • 将开始 block 的剩余部分放在 if 语句中
  • 在开始 block 之前执行计算

似乎有很多关于 breaking out of blocks 的相关问题,但我找不到可以回答这个特定版本的问题(可能是因为这是不可能的)。

最佳答案

我认为,如果您将所有这些逻辑都放入其自己的方法中,您将会避免很多冲突:

def foo
  @foo ||= compute_foo
end

def compute_foo
  puts "running"

  return "leaving early" if true # would be some sort of calculation

  # Other calculations
end

这将计算与内存分离,使其更易于测试和推理,这是 Ruby 和其他语言中相当常见的设计模式。

当然,有多种方法可以满足您的要求。最明显的解决方案是立即调用匿名过程:

def foo
  @foo ||= (proc do
    puts "running"

    next "leaving early" if true # would be some sort of calculation

    # Other calculations
  end)[] # or .call or .()
end

但是您肯定不会帮您自己或此代码的任何 future 维护者任何忙。

关于ruby - 尽早突破开始/结束 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55735695/

相关文章:

java - 使用 BigIntegers 和 memoization 调用递归方法时获取 NULL

haskell - 内存一个以集合作为参数的函数

ruby-on-rails - Ruby:强制 open-uri 返回 IPv4 地址

ruby - 如何设置可以在 Rails 中的 Controller 和模型中访问的 "global"变量

mysql - 如何在 Ruby/Rails activerecord sql 条件中包含反斜杠?

python - python 2.7的内存库

ruby-on-rails - 在 Rails 引擎中加载多个配置文件

ruby-on-rails - rails 4.2 : Eager-loading has_many relation with STI

algorithm - 为什么记忆化不能提高归并排序的运行时间?

reactjs - 在 props 中传递引用类型会使 React.memo 无用吗?