Ruby 2.3.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Kernelモジュール > caller_locations

module function Kernel.#caller_locations

caller_locations(start = 1, length = nil) -> [Thread::Backtrace::Location] | nil[permalink][rdoc]
caller_locations(range) -> [Thread::Backtrace::Location] | nil

現在のフレームを Thread::Backtrace::Location の配列で返します。引数で指定した値が範囲外の場合は nil を返します。

[PARAM] start:
開始フレームの位置を数値で指定します。
[PARAM] length:
取得するフレームの個数を指定します。
[PARAM] range:
取得したいフレームの範囲を示す Range オブジェクトを指定します。


def test1(start, length)
  locations = caller_locations(start, length)
  p locations
  p locations.map(&:lineno)
  p locations.map(&:path)
end

def test2(start, length)
  test1(start, length)
end

def test3(start, length)
  test2(start, length)
end

caller_locations # => []
test3(1, nil)
# => ["/Users/user/test.rb:9:in `test2'", "/Users/user/test.rb:13:in `test3'", "/Users/user/test.rb:17:in `<main>'"]
# => [9, 13, 17]
# => ["/Users/user/test.rb", "/Users/user/test.rb", "/Users/user/test.rb"]
test3(1, 2)
# => ["/Users/user/test.rb:9:in `test2'", "/Users/user/test.rb:13:in `test3'"]
# => [9, 13]
# => ["/Users/user/test.rb", "/Users/user/test.rb"]
test3(2, 1)
# => ["/Users/user/test.rb:13:in `test3'"]
# => [13]
# => ["/Users/user/test.rb"]

[SEE_ALSO] Thread::Backtrace::Location, Kernel.#caller