Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Method | source_location

概要

Method#source_location -> [String, Fixnum] | nil

詳細

ソースコードのファイル名と行番号を配列で返却。
対象オブジェクトがnativeの場合はnilを返却。

サンプルコード

1.rb

require 'tbpgr_utils'
require './2'

class Hoge1
  def hoge; end
end

h1 = Hoge1.new
h2 = Hoge2.new
s = String.new

bulk_puts_eval binding, <<-EOS
h1.method(:hoge).source_location
h2.method(:hoge).source_location
s.method(:upcase).source_location
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

2.rb

class Hoge2
  def hoge; end
end

出力

h1.method(:hoge).source_location # => ["%some_path%/1.rb", 5]
h2.method(:hoge).source_location # => ["%some_path%/2.rb", 2]
s.method(:upcase).source_location # => nil