Ruby 2.6 の変更点 - TracePoint

Ruby2.6アドベントカレンダーの8日目の記事です。

qiita.com

TracePoint

TracePoint#parameters 追加

https://bugs.ruby-lang.org/issues/14694

メソッド呼び出し時、ブロック実行時のパラメータを返します。

tp = TracePoint.new(:call) do |t|
  p [t.method_id, t.parameters]
end
def hoge(a, b=nil)
end
tp.enable
hoge(1, 2)  #=> [:hoge, [[:req, :a], [:opt, :b]]]

TracePoint#enable:target, :target_line キーワード引数追加

https://bugs.ruby-lang.org/issues/15289

:target は指定したメソッド等だけ処理をします。

def hoge
end
def fuga
end
tp = TracePoint.new(:call) do |t|
  p t
end
tp.enable(target: method(:hoge))
hoge   # #<TracePoint:call `hoge'@/tmp/a.rb:1> が表示される
fuga   # 表示されない

:target_line:target と組み合わせて、指定した行だけ処理をします。

def hoge
  1.to_s
  2.to_s
  3.to_s
end
tp = TracePoint.new(:call, :line){|t| p t }

tp.enable(target: method(:hoge)) do
  hoge
end
#<TracePoint:call `hoge'@/tmp/a.rb:1>
#<TracePoint:line@/tmp/a.rb:2 in `hoge'>
#<TracePoint:line@/tmp/a.rb:3 in `hoge'>
#<TracePoint:line@/tmp/a.rb:4 in `hoge'>

tp.enable(target: method(:hoge), target_line: 3) do
  hoge
end
#<TracePoint:line@/tmp/a.rb:3 in `hoge'>