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

时间:2015-08-31 04:45:06

标签: ruby methods self

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

为简洁起见,我非常简化/修改了我的代码。

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

一如既往!

1 个答案:

答案 0 :(得分:2)

在这种情况下,标准方法是使用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