从 Ruby 中生成/修改 Ruby 源文件

发布于 2024-12-27 08:03:43 字数 134 浏览 4 评论 0原文

从 ruby​​ 中生成和/或解析和修改 Ruby 源文件的最可靠方法是什么?

也就是说,我想创建一个新的 ruby​​ 源文件或更改源文件中的类中的几行代码,例如添加或删除方法或调用或其他任何内容。

也许有一个图书馆吗?

What is the most reliable way to generate and/or parse and modify a Ruby source file from within ruby?

That is, I want to e.g. create a new ruby source file or change a few lines of code in a class in a source file to e.g. add or remove methods or calls or whatever.

Is there a library for this perhaps?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第七度阳光i 2025-01-03 08:03:43

Ruby2Ruby 就是这样的宝石。可能还有其他人。从自述文件中:

require 'rubygems'
require 'ruby2ruby'
require 'ruby_parser'
require 'pp'

ruby      = "def a\n  puts 'A'\nend\n\ndef b\n  a\nend"
parser    = RubyParser.new
ruby2ruby = Ruby2Ruby.new
sexp      = parser.process(ruby)

pp sexp

p ruby2ruby.process(sexp)

## outputs:

s(:block,
 s(:defn,
  :a,
  s(:args),
  s(:scope, s(:block, s(:call, nil, :puts, s(:arglist, s(:str, "A")))))),
 s(:defn, :b, s(:args), s(:scope, s(:block, s(:call, nil, :a, s(:arglist))))))
"def a\n  puts(\"A\")\nend\ndef b\n  a\nend\n"

Ruby2Ruby is one such gem. There may be others. From the readme file:

require 'rubygems'
require 'ruby2ruby'
require 'ruby_parser'
require 'pp'

ruby      = "def a\n  puts 'A'\nend\n\ndef b\n  a\nend"
parser    = RubyParser.new
ruby2ruby = Ruby2Ruby.new
sexp      = parser.process(ruby)

pp sexp

p ruby2ruby.process(sexp)

## outputs:

s(:block,
 s(:defn,
  :a,
  s(:args),
  s(:scope, s(:block, s(:call, nil, :puts, s(:arglist, s(:str, "A")))))),
 s(:defn, :b, s(:args), s(:scope, s(:block, s(:call, nil, :a, s(:arglist))))))
"def a\n  puts(\"A\")\nend\ndef b\n  a\nend\n"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文