使用块/ proc/lambda进行Ruby双管分配?

Mis*_*ker 18 ruby syntax block operators variable-assignment

能够写出来真的很好

@foo ||= "bar_default"
Run Code Online (Sandbox Code Playgroud)

要么

@foo ||= myobject.bar(args)
Run Code Online (Sandbox Code Playgroud)

但我一直在寻找是否有办法写出类似的东西

@foo ||= do
  myobject.attr = new_val
  myobject.other_attr = other_new_val
  myobject.bar(args)
end
Run Code Online (Sandbox Code Playgroud)

在实际的功能代码中大致相当于类似的东西

@foo = if !@foo.nil?
         @foo
       else
         myobject.attr = new_val
         myobject.other_attr = other_new_val
         myobject.bar(args)
       end
Run Code Online (Sandbox Code Playgroud)

我想我可以编写自己的全局方法,如"getblock"来包装并返回任何常规块的结果,但我想知道是否已经有一种内置的方法来执行此操作.

小智 43

你可以使用begin.. end:

@foo ||= begin
  # any statements here
end
Run Code Online (Sandbox Code Playgroud)

或者可能考虑将块的内容分解为单独的方法.