运行/启动 ruby​​ 时自动需要一个类

发布于 2024-08-12 04:06:26 字数 273 浏览 4 评论 0原文

我正在一些 Ruby 类中做一些猴子修补,我希望每当我运行 Ruby 时自动包含这些修补程序。

例如:

我将方法trim添加到String中。我希望能够做到这一点:

ruby​​ -e 'puts " aaaa ".trim'

我不想这样做:

ruby​​ -e 'require "monkey.rb";放置“ aaaa”.trim'

每当我启动 ruby​​ 时是否都包含我的猴子补丁? irb 怎么样?

谢谢!

I am doing some monkey patching in some of Ruby classes and I would like that to be included AUTOMATICALLY whenever I run ruby.

For example:

I added the method trim to String. I want to be able to do this:

ruby -e 'puts " aaaa ".trim'

I don't want to do this:

ruby -e 'require "monkey.rb"; puts " aaaa ".trim'

Is there anyway to include my monkey patches evertime I start ruby? How about irb?

Thanks!

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

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

发布评论

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

评论(2

眼睛会笑 2024-08-19 04:06:26

rubyirb 都采用 -r 选项,让您在运行这些可执行文件时指定要加载的库。如果您想自动加载 monkey.rb 库,您可以通过调用 $ ruby​​ -r Monkey 启动 ruby (假设 Monkey.rb 位于您的 $RUBYLIB 路径中。如果您不想每次都这样做,您可以在 shell 配置文件中设置一个别名(例如在 Bash 中)。 ),您可以添加:

alias ruby='ruby -r monkey'

ruby and irb both take a -r option that lets you specify a library to load when running those executables. If you want to automatically load your monkey.rb library, you can start ruby with the invocation $ ruby -r monkey (assuming monkey.rb is in your $RUBYLIB path. If you don't want to do that each time, you can set up an alias in your shell config file. For example (in Bash), you could add:

alias ruby='ruby -r monkey'
二智少女猫性小仙女 2024-08-19 04:06:26

irb 可能是您可以最简单地完成此操作的地方。使用 irb 时,您可以使用初始化文件来存储您想要在每次启动时运行的任何内容。在你的主目录(“cd ~”)中,创建一个名为“.irbrc”的文件,然后放入“require 'monkey.rb'”语句,这样就可以了。从那时起,当您启动 irb 时,它将首先运行该脚本中的任何内容。

irb is probably the place where you can do this most simply. When using irb, you can use an initialization file to store anything you want run on every startup. In your home directory ("cd ~"), create a file called ".irbrc", and drop in your "require 'monkey.rb'" statement, that should do it. From then on when you start up irb, it will run anything in that script first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文