【问题标题】:Get what method called current method [duplicate]获取什么方法称为当前方法[重复]
【发布时间】:2013-01-21 16:23:32
【问题描述】:

可能重复:
How to get the name of the calling method?

在下面的例子中,我如何知道什么方法叫做 foo?

class Example
  def initialize
  end

  def foo
    puts "Hello World"  
  end

  def bar
    foo 
  end

  def cats
    bar      
  end
end

Example.new.cats 打印条。我正在尝试获取整个调用堆栈。例如。猫 -> 酒吧 -> foo

更新:

这行得通: puts caller[0..1]

Hello World
(irb):11:in `bar'
(irb):15:in `cats'

【问题讨论】:

  • 应该在运行时决定。

标签: ruby


【解决方案1】:

例如使用:puts caller[0] 这将为您提供呼叫者的信息。

【讨论】:

  • 这适用于最后一种方法,但不会显示整个调用堆栈。 Example.new.cats 将打印 bar。我正在寻找类似“cats -> bar -> foo”的东西
  • puts caller[0..1] 怎么样?
  • 调用者[0..1] 有效!谢谢你:)
  • 要获得完整的跟踪,请执行 caller[0..(caller.length-1)]
猜你喜欢
  • 2012-11-16
  • 2016-03-13
  • 2011-01-04
  • 2023-03-10
  • 1970-01-01
  • 2010-10-01
  • 2021-02-09
  • 2010-09-19
  • 2016-11-01
相关资源
最近更新 更多