I'd like to be able to return from the calling method while still inside the called method.
Example :
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
Is there a simple way to achieve that ?
The "dirty" way I'm using at the moment is this :
def calling_method
# stuff
called_method and return
# more stuff
end
def called_method
# stuff
return false if foo
# more stuff
end
But this isn't fully satisfying as I have to do a and return
in the calling method.
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.
The purpose of the . call method is to invoke/execute a Proc/Method instance.
I think, you can't do that.
The only way you can do that (at least I can think of right now) is, by using what you are calling dirty
way of doing it.
Actually, do_something and return
is a pretty common pattern/use case that you would see in Ruby/Rails code.
So, IMO, this is the way to go:
def calling_method
# stuff
called_method and return
# more stuff
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With