Ruby で pry を使ってみる
Ruby
Published: 2019-09-02

やったこと

gem の pry を使ってデバッグしてみます。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

調査

gem のインストール

$ gem install pry-byebug

ruby ファイルの準備

ruby-pry.rb

require 'pry'

class Sample
  attr_accessor :hoge, :fuga

  def initialize
    @hoge = 'hogehoge1'
    @fuga = 'fugafuga2'
  end

  def hey
    'hey'
  end
end

s = Sample.new
binding.pry

p s.hey
s.hoge = 'hogehoge'
p 'end'

ファイル実行

$ ruby ruby-pry.rb

From: /path/ruby-pry.rb @ line 19 :

    14: end
    15:
    16: s = Sample.new
    17: binding.pry
    18:
 => 19: p s.hey
    20: s.hoge = 'hogehoge'
    21: p 'end'

[1] pry(main)> step

From: /path/ruby-pry.rb @ line 12 Sample#hey:

    11: def hey
 => 12:   'hey'
    13: end

[1] pry(#<Sample>)> next
"hey"

From: /path/ruby-pry.rb @ line 20 :

    15:
    16: s = Sample.new
    17: binding.pry
    18:
    19: p s.hey
 => 20: s.hoge = 'hogehoge'
    21: p 'end'

[1] pry(main)> s.hoge
=> "hogehoge1"
[2] pry(main)> next

From: /path/ruby-pry.rb @ line 21 :

    16: s = Sample.new
    17: binding.pry
    18:
    19: p s.hey
    20: s.hoge = 'hogehoge'
 => 21: p 'end'

[2] pry(main)> s.hoge
=> "hogehoge"
[3] pry(main)> exit
"end"
  • step: 関数の中に入る
  • next: 次の行を実行
  • exit: 終了

参考