LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby】コールスタックを調査したい時(デバック)

Posted at

Rubyのコードを読んでいて、「これはどれから呼ばれているんだろう?」
と思ったときに良い方法があったので、忘備録として残しておく。

組み込み関数callerを使う

callerを使う事で呼び出し元の情報を文字列の配列として取得できる。

サンプルプログラム(callstack_test.rb)

class TestClass
  def foo
     bar
  end

  def bar
    baz
  end

  def baz
    puts caller(0)
  end
end

TestClass.new.foo

rubyを実行

$ ruby callstack_test.rb
test.ruby:11:in `baz'
test.ruby:7:in `bar'
test.ruby:3:in `foo'
test.ruby:15:in `<main>'

callerの引数の指定によって、呼び出し元を変更できます。
(呼び出し元を含める場合は0を指定します。)
引数によって呼び出し元を変えることもできるが01以外はそんなに使わないと思う。

caller(0)で実行(呼び出し元を含める)

test.ruby:11:in `baz'
test.ruby:7:in `bar'
test.ruby:3:in `foo'
test.ruby:15:in `<main>'

caller(1)で実行(呼び出し元を含めない)

test.ruby:7:in `bar'
test.ruby:3:in `foo'
test.ruby:15:in `<main>'

caller(2)で実行(引数によって呼び出し元を指定できる)

test.ruby:3:in `foo'
test.ruby:15:in `<main>'

参考文献

Ruby 2.5.0 リファレンスマニュアル
https://rurema.clear-code.com/2.5.0/method/Kernel/m/caller.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0