Ruby: return from call method

I would 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 an easy way to achieve this?

The dirty way I'm currently using 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 is not completely satisfying, as I have to execute and returnin the calling method.

+4
source share
3 answers

I think you cannot do this.

The only way you can do this (at least I can think right now) is that you invoke a way dirtyto do this.

, do_something and return - /, Ruby/Rails.

, IMO, :

def calling_method
  # stuff
  called_method and return
  # more stuff
end
+3

, , . :

# You don't need to specify &block here, it works the same if you omit it
# I added it for clarity
def calling_method(&block)
  puts 'before'
  puts yield
  puts 'after'
end

calling_method :

,

calling_method { 3 }
# before
# 3
# after
# => nil

, , next :

calling_method { next 23 }
# before
# 23
# after
# => nil

next return procs. proc ( nil ).

, , , break :

p calling_method { break 23 }
# before
# => 23

break Ruby, , proc AND, , , , break.

, , , called_method, calling_method, .

, called_method and return .

+2

.

def calling_method
  # stuff
  lambda { called_method }
  # more stuff
end
0

Source: https://habr.com/ru/post/1614425/


All Articles