Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

メソッドがどのクラス|モジュールにくっついているか調べる

Rubyにおいては、メソッドはMedhodクラスという入れ物で管理されています。
こいつをつかうと、

buff = String.new.method(:upcase)
#String#upcase()

Awesome_printのapメソッドのようなカーネルにくっついているメソッドもこの通り。

buff = AwesomePrint.method(:ap)
#Module (Kernel)#ap(object, *options)

ソースの位置を確認

組み込みのものでなければソースの位置を確認する事もできます。
管理権限の問題なのか、pryのcatコマンドでは確認できませんでしたが…*1

m = AwesomePrint.method(:ap)
m.source_location
#[
#    [0] "/Users/shuzo_kino/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/awesome_print-#1.6.1/lib/awesome_print/core_ext/kernel.rb",
#    [1] 19
#]

pryならば、catでその内容を確認する事もできます。

 cat #{m.source_location[0]}
# Copyright (c) 2010-2013 Michael Dvorkin
#
# Awesome Print is freely distributable under the terms of MIT license.
# See LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
module Kernel

  def ai(options = {})
    ap = AwesomePrint::Inspector.new(options)
    awesome = ap.awesome self
    if options[:html]
      awesome = "<pre>#{awesome}</pre>"
      awesome = awesome.html_safe if defined? ActiveSupport
    end
    awesome
  end
  alias :awesome_inspect :ai

  def ap(object, options = {})
    puts object.ai(options)
    object unless AwesomePrint.console?
  end
  alias :awesome_print :ap

  module_function :ap
end

*1:訂正。単に文字を囲い損ねただけです。初歩的ですね…