Rubyでメソッドのソースコードを簡単に取得できます。
次架空のクラスを想像してみて:
class Klass
def self.foo
:foo
end
def bar
:bar
end
end
あなたが見ることができるように、このクラスは2つのメソッドがあります
#barインスタンスメソッドを
.method
と.instance_method
を使用してプログラムにアクセスしてくださいmatically:
m1 = Klass.method :foo
=> #<Method: Klass.foo>
m2 = Klass.instance_method :bar
=> #<UnboundMethod: Klass#bar>
あなたはそれらのソースコードを表示する.source
メソッドを使用することができます。
puts m1.source
def self.foo
:foo
end
=> nil
puts m2.source
def self.bar
:bar
end
=> nil
Rubyはオープンクラスと動的ローディングを持っているので、あなたはまた、実行時に変更する方法を追加したり、 することができます。ただ、クラスを再オープンし、メソッドを再定義:
Klass.foo
=> :foo
class Klass
def self.foo
:foobar
end
end
Klass.foo
=> :footer
以前クラスで定義された他の方法は影響を受けません。
Klass.bar
=> :bar
WARNING:実行時にクラスの振る舞いを再定義(も "と呼ばれますMonkey Patching ") は非常に強力なツールですが、やはりやや危険です。現在のバージョンのRuby は、これを「改良」と呼ぶより制御された方法をサポートしています。
あなたはlearn more about using refinements here
はStackOverflowの上で同様の質問を参照してくださいすることができますhttp://stackoverflow.com/questions/4740684/ruby-get-source-codeまたはhttp://stackoverflow.com/questions/3393096/how -c-i-get-source-code-of-a-methods-dynamic-and-the-file-this-mまたはhttp://stackoverflow.com/questions/4719649/ruby-print-source -codeまたはhttp://stackoverflow.com/questions/1164903/find-the-source-of-eval-code ... – mliebelt