LoginSignup
204

More than 3 years have passed since last update.

pry-byebugでrubyをデバッグする

Last updated at Posted at 2016-03-03

pry-byebugとは

pryでデバッグするためのプラグイン
pry-debuggerの後継らしい
GitHub https://github.com/deivid-rodriguez/pry-byebug

pryとは

irbのように対話的にrubyを実行するためのツール
irbに比べてドキュメントが見れたりシンタックスハイライトが効いたりする

pry-byebugをインストールする

gem install pry-byebug

pry-byebugを使う

デバッグしたいコードにrequire 'pry'を追加する
あとは、ブレークポイントをうちたい場所にbinding.pryを書いて実行すればその箇所で処理が止まってくれてpryが起動します

sample.rb
#!/usr/bin/env ruby

require "thor"
require "pry"

x = 10
y = 20
z = 30

binding.pry # ここ
area = (x*y + y*z + z*x) * 2
volume = x * y * z
print "area: ", area, "\n"
print "volume: ", volume, "\n"

これを実行すればブレイクポイントを打ったとこで処理が止まる

     6: x = 10
     7: y = 20
     8: z = 30
     9:
    10: binding.pry
=>  11: area = (xy + yz + zx)  2
    12: volume = x * y * z
    13: print "area: ", area, "\n"
    14: print "volume: ", volume, "\n"
変数の値を確認する

変数名を打てば変数には入っている値を確認できます

[1] pry(main)> area
=> 2200
pry-byebugで使えるコマンド
next
次の行を実行
step
次の行かメソッド内に入る
continue
プログラムの実行をcontinueしてpryを終了
finish
現在のフレームが終わるまで実行

毎回nextなどを打つのが面倒くさいときは

~/.pryrcを作成しておくと楽です

.pryrc
if defined?(PryByebug)
  Pry.commands.alias_command 's', 'step'
  Pry.commands.alias_command 'n', 'next'
  Pry.commands.alias_command 'f', 'finish'
  Pry.commands.alias_command 'c', 'continue'
end

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
204