[英]Ruby double pipe assignment with block/proc/lambda?
It is really nice to be able to write out 能够写出来真的很好
@foo ||= "bar_default"
or 要么
@foo ||= myobject.bar(args)
but I have been looking to see if there is a way to write something like 但我一直在寻找是否有办法写出类似的东西
@foo ||= do
myobject.attr = new_val
myobject.other_attr = other_new_val
myobject.bar(args)
end
roughly equivilent in actually functional code to something like 在实际的功能代码中大致相当于类似的东西
@foo = if !@foo.nil?
@foo
else
myobject.attr = new_val
myobject.other_attr = other_new_val
myobject.bar(args)
end
And I suppose I could write my own global method like "getblock" to wrap and return the result of any general block, but I'm wondering if there is already a built-in way to do this. 我想我可以编写自己的全局方法,如“getblock”来包装并返回任何常规块的结果,但我想知道是否已经有一种内置的方法来执行此操作。
You can use begin
.. end
: 你可以使用
begin
.. end
:
@foo ||= begin
# any statements here
end
or perhaps consider factoring the contents of the block into a separate method. 或者可能考虑将块的内容分解为单独的方法。
I usually write it like this: 我通常这样写:
@foo ||= (
myobject.attr = new_val
myobject.other_attr = other_new_val
myobject.bar(args)
)
@foo ||= unless @foo
myobject.attr = new_val
myobject.other_attr = other_new_val
myobject.bar(args)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.