是否有与Nokogiri类似的解析Ruby代码的东西?

Nokogiri太棒了。 我可以做像#css('.bla') ,它将返回第一个匹配的元素。

现在我们需要对Ruby源代码进行一些解析 – 查找类中的所有方法等。我们使用的是ruby_parser gem,但它只是梳理你的源代码并吐出S表达式。 对于这些S表达式有什么像Nokogiri这样的东西可以做“返回第一个方法的S表达式,发现名为’foo’”吗?

我唯一能想到的是Adam Sanderson的SExpPath库 。

虽然我接受Jörg的答案,因为它更完整,但我最终发现了我最终使用的其他东西。 ruby_parser安装一个名为sexp_processor的依赖gem(它在这个gem中实际定义了Sexp类)。 如果你查看类文档 ,有一些方法可以帮助基本的Ruby查找程序。 这是一个例子:

 class Sexp def name # convenience method self.sexp_body.first end end # Print out all instance methods within classes. Beware - if "code" sexp itself # is a class, it will NOT be included! code = RubyParser.new.parse(IO.read('/src/file')) code.each_of_type(:class){ |klass| klass.each_of_type(:defn){ |meth| puts meth.name } } 

我对您正在寻找的gem一无所知,但您可以使用instance_methods找到类中的所有方法:

 class Foo def bar end end irb(main):005:0> Foo.instance_methods - Object.instance_methods => [:bar] 

你可以检查rubinius解析器,它可以帮助你做你想要的。