Ruby-on-rails 如何从 IRB 运行 .rb 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6149850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a .rb file from IRB?
提问by Katrina
I am starting out with Ruby on Rails. I am currently going through a tutorial where it says that I have to run a .rb file from IRB and that that will create a .xml file in my current directory.
我开始使用 Ruby on Rails。我目前正在阅读一个教程,它说我必须从 IRB 运行一个 .rb 文件,这将在我的当前目录中创建一个 .xml 文件。
My question is how do I run a .rb file in IRB?
And do I have to be in the directory where this .rb file lives when I run it in IRB?
我的问题是如何在 IRB 中运行 .rb 文件?
当我在 IRB 中运行它时,我是否必须在这个 .rb 文件所在的目录中?
I tried the following: just typing irbon the command line in the directory of the file. That starts an IRB session as far as I understand.
Then I typed irb "filename.rb"which went through but didn't create anything in the current directory but at least it didn't give any errors.
我尝试了以下操作:只需irb在文件目录中的命令行上键入即可。据我所知,这将启动 IRB 会议。
然后我输入irb "filename.rb"which 通过但没有在当前目录中创建任何内容但至少它没有给出任何错误。
I also tried a whole bunch of other stuff that plain gave me errors. So I don't think I can solve this myself and googling the matter didn't help at all.
我还尝试了一大堆其他东西,这些东西显然给了我错误。所以我认为我自己无法解决这个问题,谷歌搜索这个问题根本没有帮助。
I am running Leopard.
我在跑豹。
回答by J-_-L
You can "run" a file in irb by just requiring or loading it.
你可以在 irb 中“运行”一个文件,只需要求或加载它。
$ irb
>> load './filename.rb'
To change your current working directory within irb, you can use FileUtils:
要在 irb 中更改当前工作目录,您可以使用FileUtils:
>> require 'fileutils'
>> FileUtils.pwd # prints working directory
>> FileUtils.cd '/path/to/somewhere' # changes the directory
回答by Gabriel Lidenor
In case you want to have your file loaded in the irbsession and you are using Ruby 2+ you can load a file in irblike this:
如果您想在irb会话中加载您的文件并且您使用的是 Ruby 2+,您可以像这样在irb 中加载一个文件:
irb -r ./the_name_of_your_file.rb
This opens an irb session with the given file loaded.
这将打开一个加载给定文件的 irb 会话。
Imagine you have file with a class like this:
想象一下,你有这样一个类的文件:
class Example
def initialize(name)
@name = name
end
def print__example
p name
end
end
You will be able to use the Example class in the irbsession.
您将能够在irb会话中使用 Example 类。
回答by Sreenivas
We can just create a .rb file in the directory which you are currently working in using any text editor and type all the code in that and then use the command ruby filename.rbin the terminal, not in the irb, then it shows the output in irb.
我们可以使用任何文本编辑器在您当前正在使用的目录中创建一个 .rb 文件,并在其中键入所有代码,然后ruby filename.rb在终端中使用该命令,而不是在 irb 中,然后它会在 irb 中显示输出。

