如何在ruby中获取源代码文本?

如何在ruby中获取源代码文本?,ruby,Ruby,受运行时编辑源代码的lisp魔力启发 我想用ruby做。看起来我无法从方法/类获取源代码, 有办法吗 我在这里编写了一个示例源代码: def helloworld n "hello #{n}" end o = Kernel.method :helloword Kernel.define_singleton_method o.name do |n| eval o.source_code.sub('hello', 'hello world') end helloworld 'halid

受运行时编辑源代码的lisp魔力启发

我想用ruby做。看起来我无法从方法/类获取源代码, 有办法吗

我在这里编写了一个示例源代码:

def helloworld n
  "hello #{n}"
end

o = Kernel.method :helloword

Kernel.define_singleton_method o.name do |n|
  eval o.source_code.sub('hello', 'hello world')
end

helloworld 'halida' #=> 'hello world halida'

您无法获取部分代码的字符串表示形式,编辑它并期望Ruby重新评估您的更改。唯一接近您想要的方法是使用
ParseTree
获取源代码的s表达式,编辑并使用
Ruby2Ruby
生成一个ruby代码字符串。它们将
def…
end
添加到字符串中,并用它调用eval

这太难了,而且在现实世界中很容易出错。但我不知道还有别的办法

注意:ParseTree只适用于Ruby 1.8。

看看gem。REPL将其用于
show方法
命令


看起来这个gem使用标准的
方法#source_location
(Ruby 1.9中提供)来定位方法并获取其源代码。显然,它不适用于动态定义的方法和C方法。有关更多信息,请参阅文档。

您可以轻松获得Ruby中方法的源代码

想象一下下面的假设类:

class Klass
  def self.foo
    :foo
  end

  def bar
    :bar
  end
end
如您所见,此类有两种方法:

  • 类方法。foo
  • 一个实例方法#bar
使用
.method
.instance\u method
以编程方式访问它们:

m1 = Klass.method :foo
=> #<Method: Klass.foo>

m2 = Klass.instance_method :bar
=> #<UnboundMethod: Klass#bar>
因为Ruby具有开放类和动态加载,所以您还可以添加或 在运行时更改方法。只需重新打开类并重新定义方法:

Klass.foo
=> :foo

class Klass
  def self.foo
    :foobar
  end
end

Klass.foo
=> :footer
以前在类中定义的其他方法将不受影响:

Klass.bar
=> :bar
警告:在运行时重新定义类行为(也称为“猴子补丁”) 是一个非常强大的工具,它也可能有点危险。Ruby的当前版本 支持一种更可控的方式,称为“改进”


您可以在Stackoverflow上看到类似的问题:或者……您完全可以获得源代码的字符串表示形式。只需对类方法使用
.method.source
,对实例方法使用
.instance\u method.source
。如果要编辑字符串并重新应用它,只需打开类重新定义方法并对新字符串使用
eval
。另请参见
class\u eval
instance\u eval
Klass.bar
=> :bar