Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby : return from calling method

Tags:

return

ruby

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.

like image 257
Mat Avatar asked Nov 04 '15 10:11

Mat


People also ask

How do you return a value from a method in Ruby?

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.

What does return in Ruby do?

Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.

What does .call do in Ruby?

The purpose of the . call method is to invoke/execute a Proc/Method instance.


1 Answers

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
like image 62
K M Rakibul Islam Avatar answered Oct 25 '22 06:10

K M Rakibul Islam