我想要一种方法来退出开始/结束 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
就退出了整个方法。使用 break
或 next
只能在循环中使用。 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/