Ruby:从调用方法返回

Mat*_*Mat 5 ruby return

我希望能够从调用方法返回而仍在被调用方法内部。

范例:

def calling_method
  # stuff
  called_method
  # more stuff
end

def called_method
  # stuff
  return_from_caller if foo # << I would like to return from calling_method
  # more stuff
end
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法可以做到这一点?

我目前使用的“肮脏”方式是这样的:

def calling_method
  # stuff
  called_method and return
  # more stuff
end

def called_method
  # stuff
  return false if foo
  # more stuff
end
Run Code Online (Sandbox Code Playgroud)

但这并不完全令人满意,因为我必须and return在调用方法中执行一个。

K M*_*lam 4

我想,你不能这么做。

你能做到这一点的唯一方法(至少我现在能想到)是使用你所说的dirty方法。

实际上,do_something and return这是您在 Ruby/Rails 代码中看到的一个非常常见的模式/用例。

所以,IMO,这是要走的路:

def calling_method
  # stuff
  called_method and return
  # more stuff
end
Run Code Online (Sandbox Code Playgroud)