如何调用刚刚从另一个方法调用的方法

How to call the method that was just called from another method

我正在尝试 运行 一个输入验证器,如果输入错误,它将重新运行 调用验证器的方法。我知道(来自类似的问题)您可以使用 .caller 方法来查找名称,但我想简单地调用调用当前方法的方法(我不需要知道它是什么name/class 是。)

为了简洁起见,我已经simplified/altered我的代码了。

def stack(input)
    if input == "A"
        puts "Good job. Back to continue on the method you were just in."
    else 
        puts "Try again. Back to the beginning of the method you were just in."
        # invoke the method that called 'stack(input)' on this instance
        # to prompt the user again from whatever method they came from.
        # { insert brilliant code here (in this case, it'd call 'overflow') }
    end
end

def overflow
    p "Misc Instructions / Prompt: Type A to continue"
    input = gets.chomp
    stack(input)
    # continuing code
end

overflow

一如既往的感谢!

在这种情况下,标准方法是使用 catchthrow

def stack(input)
  case input
  when "A"
    puts "Good job. Back to continue on the method you were just in."
    throw :continue
  else 
    puts "Try again. Back to the beginning of the method you were just in."
  end
end

def overflow
  catch(:continue) do loop do
    p "Misc Instructions / Prompt: Type A to continue"
    stack(gets.chomp)
  end end
  # continuing code
end